Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The 'this' pointer in the initialization list of the constructor

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.

like image 478
Hemant Bhargava Avatar asked Jan 12 '17 14:01

Hemant Bhargava


People also ask

What is constructor initialization list?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.

Can I use this pointer in the constructor?

Some people feel you should not use the this pointer in a constructor because the object is not fully formed yet. However you can use this in the constructor (in the { body } and even in the initialization list) if you are careful.

What is * this pointer in C++?

The this pointer is a pointer accessible only within the nonstatic member functions of a class , struct , or union type. It points to the object for which the member function is called.

What is an initialization list in C++?

The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters.


2 Answers

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. } 
like image 69
Hatted Rooster Avatar answered Sep 30 '22 11:09

Hatted Rooster


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

like image 41
Potatoswatter Avatar answered Sep 30 '22 10:09

Potatoswatter