Home > front end >  What does this passage from cppreference.com (Default arguments) mean?
What does this passage from cppreference.com (Default arguments) mean?

Time:01-31

From cppreference page on default arguments:

Non-static class members are not allowed in default arguments (even if they are not evaluated), except when used to form a pointer-to-member or in a member access expression:

int b;
class X
{
    int a;
    int mem1(int i = a); // error: non-static member cannot be used
    int mem2(int i = b); // OK: lookup finds X::b, the static member
    static int b;
};

I can't understand "except when used to form a pointer-to-member or in a member access expression". And the example does not give the relevant code.

CodePudding user response:

The first part means that you are allowed to form a pointer-to-member to one of the non-static members, e.g.:

class X
{
    int a, b;
    int mem1(int X::* i = &X::a);
    //...
};

A pointer-to-member is a rather obscure part of the language. You have maybe seen member function pointers, but you are also allowed to form such member pointers to data members as above.

The member pointer doesn't refer to the member of the current instance of the class, but needs to be combined with the .* or ->* operators to give the corresponding member of an instance, e.g.:

int X::mem1(int X::* i = &X::a) {
    // same as `return a;` if called with default argument
    // but if called with `mem1(&X::b)` same as `return b;`
    return this->*i; 
}

The second part probably just means that it is ok to refer to the member of another instance of the class via the usual member access expressions (using . or ->). The exception doesn't allow referring to the current instance's members since this is also not allowed in the default argument:

class X
{
    int a;
    static X x;
    int mem1(int i = x.a); // ok, `.` is member access
    int mem2(int i = this->a); // not ok because of `this`, but `->` is member access
};

CodePudding user response:

Forming a pointer-to-member:

int mem3(int X::*pointer_to_member = &X::a);

Used in a member-access expression:

X global;

int mem4(int i = global.a);

Demo

  •  Tags:  
  • Related