views:

156

answers:

4

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?

+8  A: 

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);
Charles Bailey
Couldn't that non-const `dflt` value be modified in code, changing the meaning of `MyFun`?
Arc
@Arc: Yes, but presumably the point of taking a non-`const` reference is to modify the passed argument; it may be an 'out' only parameter. It's difficult to think of a case where this would have a legitimate use but it is allowed by the language.
Charles Bailey
Sure, though in C++ it is not syntactically clear whether it is a 'ref' or an 'out'. If it is indeed an output-only parameter, then you're solution is semantically correct since changing `dflt` in code won't change anything.
Arc
+2  A: 

It is not allowed, because you have a non-const reference. It is possible if you would have a const reference

bool MyFun(int nMyInt, char* szMyChar, const double& nMyReferencedDouble = 0.0)

but I presume that this is not what you need.

Cătălin Pitiș
A: 

No it is not. Basically, reference is something that should be existing. In your case, if you don't pass a variable for the fun() then nMyReferencedDouble would not refer to any thing.

Jagannath
+5  A: 

You could overload the function instead.

// Definition
bool MyFun(int nMyInt, char* szMyChar, double& nMyReferencedDouble);

// Overload
bool MyFun(int nMyInt, char* szMyChar)
{
    double nMyReferencedDouble = 0.0;
    MyFun( nMyInt, szMyChar, nMyReferencedDouble );
}

This is how you get around the current limitations of no default values in C# and works equally well for semantic limitations in C++.

Arc
+1: nice and clean. I was going to suggest this very thing.
D.Shawley