1

Possible Duplicate:
Nonstatic member as a default argument of a nonstatic member function
Why can member variables not be used as defaults for parameters?

Ok I apologize in advance if I am not seeing something very simplistic here or forgetting some fundamental rule of C++ but I am not sure why this does not work as expected.

Here is a example of code that I can't get to work

class Foo
{
private:
    Bar *ptrBar;
public:
    void doSomething(int x, Bar *p = ptrBar);
}

The compiler is having an issue with the default parameter to this function. Is there some reason why this wouldn't work.

Basically doSomething would do some operation on a Bar object, and I want it to be the one pointed to by ptrBar by default. Everything seems sound unless I am forgetting something?

Community
  • 1
  • 1
MadOgre
  • 482
  • 6
  • 15

2 Answers2

5

You're not allowed to use class members as default parameters, nor this.

8.3.6 Default arguments [dcl.fct.default]

[...] Similarly, a non-static member shall not be used in a default argument, even if it is not evaluated, unless it appears as the id-expression of a class member access expression (5.2.5) or unless it is used to form a pointer to member (5.3.1). [...]

The best workaround would be to use overloading:

class Foo
{
private:
    Bar *prtBar;
public:
    void doSomething(int x, Bar *p);
    void doSomething(int x)
    {
        soSomething(x, ptrBar);
    }
}
Luchian Grigore
  • 236,802
  • 53
  • 428
  • 594
  • Yes that is how I dealt with it. But what that did is created a whole bunch of overloaded functions. I was just hoping to de-clutter my code. – MadOgre Dec 16 '12 at 09:01
1

At the time the compiler is evaluating this, ptrBar is not set. Therefore your default parameter has no default value.

Why not use a default of null and if p in doSomething() is null then use the ptrBar member.

John3136
  • 27,345
  • 3
  • 44
  • 64