Default value to a parameter while passing by reference in C++

Sony picture Sony · Jun 29, 2009 · Viewed 129.8k times · Source

Is it possible to give a default value to a parameter of a function while we are passing the parameter by reference. in C++

For example, when I try to declare a function like:

virtual const ULONG Write(ULONG &State = 0, bool sequence = true);

When I do this it gives an error:

error C2440: 'default argument' : cannot convert from 'const int' to 'unsigned long &' A reference that is not to 'const' cannot be bound to a non-lvalue

Answer

anon picture anon · Jun 29, 2009

You can do it for a const reference, but not for a non-const one. This is because C++ does not allow a temporary (the default value in this case) to be bound to non-const reference.

One way round this would be to use an actual instance as the default:

static int AVAL = 1;

void f( int & x = AVAL ) {
   // stuff
} 

int main() {
     f();       // equivalent to f(AVAL);
}

but this is of very limited practical use.