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.
Simply because there's no need, an initializer list can already disambiguate because its syntax is strict:
So you can just change it to:
this->memberis only really used when the programmer needs to help the compiler to disambiguate, for example, if your constructor would've looked like:Your
A::awouldn't have been initialized now, oops!You would need
thisto help the compiler: