1

Possible Duplicate:
Nonstatic member as a default argument of a nonstatic member function

Ok. So I'm having problems understanding how to accomplish a seemingly simple task... Here is what I want to accomplish:

#include <iostream>

using namespace std;

class A{
private:
    int _x;
public:
    A(int x){
        _x = x;
    }

    void test(int x=_x){
        cout << x << endl;
    }
};

int main(){
    A a(3);
    a.test();
}

The compiler complains about the int x=_x part saying error: invalid use of non-static data member A::_x

So how do I use a default parameter like this?

Thanks.

Community
  • 1
  • 1
poy
  • 10,063
  • 9
  • 49
  • 74

3 Answers3

14

You can't do that.

You can however have an overload for test that takes no parameters.

void test(){
    test(_x);
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
3

You cannot do that. However if you declare _x as static data member as:

static int _x; //_x is static data member now!

Then you can do that, i.e you can use _x as default value for parameters in your member functions.

A nice example from the C++ Standard itself. Quoting from section §8.3.6/9 :

Similarly, a nonstatic member shall not be used in a default argument expression, 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). [Example: the declaration of X::mem1() in the following example is ill-formed because no object is supplied for the nonstatic member X::a used as an initializer.

int b;
class X {
   int a;
   int mem1(int i = a); // error: nonstatic member a used as default argument
   int mem2(int i = b); // OK; use X::b
   static int b;
};

The declaration of X::mem2() is meaningful, however, since no object is needed to access the static member X::b.

Hope it helps.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 1
    Ah, that example is perfect. I wonder if C++0x (or future versions) going to address any of these kinds of limitations. – poy Apr 11 '11 at 18:46
0

Does your function have a sentinel (-1)?

void test(int x=-1)
{
    if(x == -1)
        x = _x;

    //Rest of code
}

You could also use:

void test(int x, bool bUseLocal=false)
{
    if(bUseLocal)
        x = _x;

    //Rest of code
}
Jess
  • 2,991
  • 3
  • 27
  • 40
  • What if the argument passed is `-1` itself? You would think no argument is passed and hence would use `_x` instead? – Nawaz Apr 11 '11 at 18:43
  • That's why I asked if there is a sentinel (a never used value). – Jess Apr 11 '11 at 18:43
  • 2
    Unfortunately I'd like to assume all values are valid. – poy Apr 11 '11 at 18:45
  • Both the approaches above are solid (Daniel/Nawaz); I've added a second option to mine as well. I like Daniel's the best though. – Jess Apr 11 '11 at 18:50