c++c++11default-valueoverloading

Using a class member as a default argument for a member function


Is there another way than manually overloading the corresponding member function and calling the first overload with the member as the argument?

I am trying something along the lines of

class test
{
    string t1="test";

    testfun( string& val = this->t1 )
    { /* modify val somehow */ }
};

Test it

Currently I guess there is no technical reason why this should not work.


Solution

  • [dcl.fct.default]/8:

    The keyword this shall not be used in a default argument of a member function.

    This is a special case of a general problem: You cannot refer to other parameters in a default argument of a parameter. I.e.

    void f(int a, int b = a) {} 
    

    Is ill-formed. And so would be

    class A
    {
        int j;
    };
    
    void f(A* this, int i = this->j) {}
    

    Which is basically what the compiler transforms a member function of the form void f(int i = j) {} into. This originates from the fact that the order of evaluation of function arguments and the postfix-expression (which constitutes the object argument) is unspecified. [dcl.fct.default]/9:

    Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated.