views:

318

answers:

4

Hi, I tried to do something like this:

int& g(int& number = 0)
{
//maybe do something with number
    return number;
}

but it doesn't work. It has to be passed by reference. Thank you for any help.

P.S. I think that "Related Questions" appearing once you type Title is a good idea, but I also think that they should be displayed only if they are related to specific language, i.e. it is less than useless for me to looking at topic with similar problem but in Ruby.

+11  A: 

If you really want to do this:

  • make the reference const, so that a temporary can be bound to it
  • put the default in the function declaration, not the definition

For example:

// header
const int & g( const int & number = 0 );


// implementation
const int & g( const int & number )
{
//maybe do something with number
    return number;
}

PS Post your complaints about how SO works on Meta, not here (for all the good it will do - answering this question indicated they STILL haven't fixed the code-after-list bug)

anon
Thanks guys for all your answers.
There is nothing we can do
+1 But the signature indicates that the OP probably want's to modify number, which won't be possibily without casting away the const.
Andreas Brinck
anon
It is a bit a funky construction anyway, but couldn't "const int " lead to a dangling reference? If I wanted to return something, I'd return a value (even when returning a class).
stefaanv
This is not good! Is isn't even a solution since even the temporary's storage will be out of scope after the function g() returns, leaving a dangling reference.
haavee
I am of the opinion that the lifetime of the temporary used as the default extends beyond the lifetime of the call. If you know better, please post a C++ Standard reference.
anon
Even if it was I'd say it is bad form to rely on exactly that behaviour - you never know wether or not it was the default that was referenced or not.
haavee
+4  A: 

You have a non-const reference, which means you can modify the referand. But your default is the constant 0.

Does it really make sense for this function to have a default?

GMan
A: 

A non-const reference cannot bind to a temporary (literal).

Here it would probably make most sense to take arguments and return by value, and leave it up to the caller to assign the result back to the variable (if they want so): k = g(k);

Perhaps you could also use two overloads, but the "default" one cannot return by reference, which might lead to some confusion:

int& g(int&);

int g()
{ 
    int arg = 0;
    return g(arg);
}
visitor
A: 
haavee