0

Hi,
I would like to write a member function with a default argument,
but the value of the default argument I would like to use is the value
of the classes data member

class testdf
{// testdf
private:
  const int _defaultVal;

public:
  testdf() : _defaultVal(1) {}
  int testMF(int arg = _defaultVal){ return arg; }

  ~testdf();
}; // testdf

The compiler plainly doesn't allow this. But it seems like a
pretty legitimate usage, so I was wondering if there was some workaround for this?
The compiler error message says that the datamember needs to be static, and if
I switch it to static it does work.

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by DavidtheRaindog
0

>>The compiler plainly doesn't allow this.

Basically, the restriction that is imposed on the default arguments (for function parameters) is that they cannot be derived from or referring to the other function parameters. And because the "this" pointer is a hidden first argument to any class member function, any non-static data member cannot be used as a default argument since it is contingent on the first "hidden" parameter of the function.

I don't know exactly why it was not allowed to create default arguments from the other function parameters (personally, I don't see any technical reason why this wouldn't be possible, but maybe there is one).

The work around is to use overloading (which is what default arguments do in effect, they result in different (implicit) overloads with fewer arguments). As in:

class testdf
{// testdf
private:
  const int _defaultVal;

public:
  testdf() : _defaultVal(1) {}
  int testMF(int arg) { return arg; }
  int testMF() { return testMF(_defaultVal); }

  ~testdf();
}; // testdf
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.