Possible Duplicate:
Default value to a parameter while passing by reference in C++
Is it possible to do something like this:
// definition
bool MyFun(int nMyInt, char* szMyChar, double& nMyReferencedDouble = 0.0);
Then the function can be called either like this:
MyFun(nMyInt, szMyChar, nMyReferencedDouble);
or like this:
MyFun(nMyInt, szMyChar);
My compiler (VS 98) complains. Is there a way to do this?
As you can only bind temporary objects to a const
reference and constant expression default arguments convert to temporary objects, you can only do this with a parameter that is a const
reference.
You can, however, overload the function and have the one which doesn't take a reference create a local named object and pass that to the overload that does take an extra reference parameter.
Actually, what I've said isn't strictly true. Default arguments are like initializers for parameters so if you had a suitable non-const double available, you could bind that to the reference parameter.
e.g.
extern double dflt;
bool MyFun(int nMyInt, char* szMyChar, double& nMyReferencedDouble = dflt);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With