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.
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.
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.
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.
The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters.
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. }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With