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.

>>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

thank you, that sounds like that will do it. Should have
thought of it myself...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.