Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

referenced argument to a function with default value in C++ [duplicate]

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?

like image 299
Sunscreen Avatar asked Dec 08 '22 04:12

Sunscreen


1 Answers

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);
like image 58
CB Bailey Avatar answered Jan 17 '23 04:01

CB Bailey