* jryden:
I can do this:
struct myInt
{
int i;
};
void func1(myInt &i = myInt());
As Victor already wrote, no you can't.
Adding to that, some compilers allow you to do that as a non-standard
extension.
If your compiler is one such, then it's a good idea to turn off that
language extension, if possible.
but not this:
void func2(int &i = int());
Generates error C2440: 'default argument' : cannot convert from 'int'
to 'int &' (Visual C++ compiler)
Right.
Can someone explain why?
Stroustrup's original explanation for why an alias for (reference to) a
non-const can't be bound to an rvalue, is that that could easily lead to
surprising results like apparently modifying the value of 42 -- while
in reality of course just modifying the temporary. I seem to recall
that Pete Becker once posted a much more forceful argument in this
group, involving function arguments and overloading. Something like
calling with an int argument for a formal unsigned& -- I can't recall
-- but now that I've mentioned it, you would not want this
void doTheThing( unsigned& x ) { x = 666; }
int main()
{
int nastyValue;
doTheThing( nastyValue );
std::cout << nastyValue << std::endl;
}
to be accepted, much less produce garbage output.
I would like a default [presumably non-const] reference parameter using
a simple type.
You can do
void func2( int& i ) { ... }
void func2() { int i = 0; func2( i ); }
or you can do
int defaultI = 0;
void func2( int& i = ::defaultI ) { ... }
or whatever.