27

I guess I am unable to understand why this is not working. I always thought that I can use 'this' pointer inside the constructor, but I never knew that I cannot use 'this' in the initialization list.

#include <iostream>

class A {
    public:
        int a;
        int b;
        A(int a = 0, int b = 0) : this->a(a), this->b(b) { }
        void print() {
        std::cout << a << ", " << b << std::endl;
    }
};

int main() {
    A a;
    a.print();
}

I am interested to know the details related to it.

Amal K
  • 4,359
  • 2
  • 22
  • 44
Hemant Bhargava
  • 3,251
  • 4
  • 24
  • 45

2 Answers2

36

Simply because there's no need, an initializer list can already disambiguate because its syntax is strict:

member(value)

So you can just change it to:

A(int a = 0, int b = 0) : a(a), b(b) {}

this->member is only really used when the programmer needs to help the compiler to disambiguate, for example, if your constructor would've looked like:

A(int a = 0, int b = 0) 
{ 
  // set local 'a' to itself
  a = a; 
}

Your A::a wouldn't have been initialized now, oops!

You would need this to help the compiler:

A(int a = 0, int b = 0) 
{ 
  this->a = a; // set A::a to local a.
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
  • I'd like to add that using `this` to access members when ambiguity is an issue is more of a Java thing. In C++, your attributes should (usually) have a name like `a_`, which reduces the above line to `a_ = a;`. To quote the [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html#Variable_Names): _Data members of classes (but not structs) additionally have trailing underscores._ – Konstantin Jan 12 '17 at 19:40
  • 13
    @KonstantinĐ.: Note that the Google C++ Style Guide is not well-respected among C++ programmers, and should not be taken as representative of what the C++ community recommends. – ruakh Jan 13 '17 at 02:27
  • @KonstantinĐ. The value of prefix/suffix naming conventions are very subjective, and often unnecessary. That's why the `this` construct exist in the first place. I would recommend Clean Code by Bob Martin for a different perspective. – drognisep Jan 13 '17 at 13:55
30

this->a is grammatically invalid because it is a member-access expression, but only an identifier is allowed there (or a type specifier, for base classes).

From the C++ standard, [class.base.init],

mem-initializer-id:
      class-or-decltype
      identifier

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • 5
    Right, and the "why" is .... because there would be absolutely no need to complicate the grammar to allow an added `this->`. In fact you'd then have to backtrack with a bunch of "... is ill-formed" rules to ban basically anything you'd just added _but_ the added `this->`. – Lightness Races in Orbit Jan 12 '17 at 23:31