Home > Mobile >  Initialization of data member in initialization section using this pointer
Initialization of data member in initialization section using this pointer

Time:01-23

#include <iostream>
#include <string>

using namespace std;

class Child {
    size_t age;
    string nation;

    public:
        Child() : age(0), nation("N/A") { }
        Child(size_t a, string nation) : age((a <= 5) ? a : 0), (this->nation)(nation) { }
        void showDet() {cout << age << endl << nation;}

};


In the 2nd constructor I am using this pointer to initialize string type member var nation but getting error "name of member or class is missing"

CodePudding user response:

Long story short: C standard doesn't allow this keyword to be used in this context.


this has well defined set of scopes it can appear in ([expr.prim.this]):

  • Scope of a (non-static) member function:
class S {
    int i;

    void foo() {
        this->i = 4;
    }
};
  • (Non-static) default member initialiser
class S {
    int i = sizeof(*this);
};

For any other context use of this is considered ill-formed by the standard. One can argue, that member initialiser list falls into a member function's scope category, however identifiers in this list have special name lookup rules ([class.base.init]/2):

Lookup for an unqualified name in a mem-initializer-id ignores the constructor's function parameter scope.

Unless the mem-initializer-id names the constructor's class, a non-static data member of the constructor's class, or a direct or virtual base of that class, the mem-initializer is ill-formed.

At the same time it means, that you can safely initialise member variables with constructor parameters of the same name:

class S {
    int i;

    S(int i): i(i) {}
};

Last, but not least, the semantic you want to use is still valid in the body of a constructor, because it's where member function scope comes into play:

class S {
    int i;

    S(int i) {
        this->i = i;
    }
};
  • Related