Default parameter to function when passing by reference

C

Chris

Suppose I have the following function signature

void foo( Bar &myBar);

and I want myBar to be an optional parameter, is there a way to do the
logical equivalent of

void foo( Bar &myBar = myBar() )

when passing by reference? Every method I've tried gives me syntax
errors.

Thanks!
 
S

smguo2001

Suppose I have the following function signature

void foo( Bar &myBar);

and I want myBar to be an optional parameter, is there a way to do the
logical equivalent of

void foo( Bar &myBar = myBar() )

when passing by reference? Every method I've tried gives me syntax
errors.

Thanks!

how about
void foo( const Bar &myBar = myBar() )
?
 
C

Chris

how about
void foo( const Bar &myBar = myBar() )
?

I guess the example I gave there should really be

void foo( Bar &myBar = Bar() );

but anyway, I have every intention of modifying that variable, so
const (while it does fix the syntax problem) is not a viable
solution. Am I stuck making a copy of that variable either by passing
by copy or making a local copy in my function?
 
V

Victor Bazarov

Chris said:
I guess the example I gave there should really be

void foo( Bar &myBar = Bar() );

but anyway, I have every intention of modifying that variable,

That is a rather strange design decision. What is it you're intended
to modify if you pass a temporary in? And if it's documented (and thus
known) that 'foo' modifies its argument, what could be the point of
calling it without an argument?
so
const (while it does fix the syntax problem) is not a viable
solution. Am I stuck making a copy of that variable either by passing
by copy or making a local copy in my function?

No, you can have a global object you'd modify the hell out of when the
caller is careless enough not to supply the argument.

V
 
P

peter koch

Suppose I have the following function signature

void foo( Bar &myBar);

and I want myBar to be an optional parameter, is there a way to do the
logical equivalent of

void foo( Bar &myBar = myBar() )

when passing by reference? Every method I've tried gives me syntax
errors.
That is because you can't do that. What is the problem with

void foo() { Bar myBar; foo(myBar);}

I actually recommend this method instead of having default parameters
in the general case. The advantage is the greater versatility if you
should ever want to pass foo as a parameter.

/Peter
 

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

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top