Passing optional argument by reference

R

Rudy Moore

Is this valid c++? f()'s argument is a reference, but has a default
value. It compiles with gcc 3.3.3

class A {};

void f(const A& a = A()) {}

int main() {
f();
return 0;
}

Thanks,

Chris
 
I

Ioannis Vranos

Rudy said:
Is this valid c++? f()'s argument is a reference, but has a default
value. It compiles with gcc 3.3.3

class A {};

void f(const A& a = A()) {}

int main() {
f();
return 0;
}



Yes. If an argument is not passed, a temporary is created which lives
till the end of the function scope.
 
S

Sumit Rajan

Rudy said:
Is this valid c++? f()'s argument is a reference, but has a default
value. It compiles with gcc 3.3.3

class A {};

void f(const A& a = A()) {}

int main() {
f();
return 0;
}


There is no problem here: as long you use const A& and not A&.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top