kiriloff
kiriloff

Reputation: 26333

c++ default parameters value

I would like to make sure that this method call is correct. I have three arguments, and one defaults to a null QString.

double funcApply(double* param, QString expr=NULL);

and the call is

funcApply(param);

In function body, I test whether second argument expr is NULL or not, and proceed accrodingly. Will this call behave as expected, or misbehave?

Thanks and regards.

Upvotes: 0

Views: 1652

Answers (2)

Bo Persson
Bo Persson

Reputation: 92381

I have errors 'redefinition of default parameter' and 'ambiguous call to overloaded function' at compile time

For some reason, you are not allowed to repeat a default argument once it is given. If you have the default value in your header file, like:

double funcApply(double* param, QString expr=NULL);

the implementation must not repeat it, but be something like

double funcApply(double* param, QString expr /*=NULL*/)
{
    // do something
}

If you actually test the expr parameter for NULL and do two different things, you might be better off with two separate functions that do these "different things"

 double funcApply(double* param);
 double funcApply(double* param, QString expr);

and avoid this problem.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258678

It depends on what you expect it to behave like.

Technically, expr will not be NULL since it's not a pointer, but its contents will be empty. (assuming you mean QString).

Of course, if you have something like #define QString char*, then expr will be NULL, but I doubt you have that.

Upvotes: 2

Related Questions