I'm learning C++ coming from a Java background (knowing a little C from many years ago)...
In Java, it's common practice to use "this" inside a constructor to distinguish the variable passed in as arguments to the constructor from the one declared in the class:
class Blabla {
private int a;
private int b;
Blabla(int a, int b){
this.a = a;
this.b = b;
}
}
I like this, because the variable Blabla.a and the one passed in as an argument to the constructor represents the same thing, so it feels logical that they should have the same name...
Is it possible to do this in C++?
Yes, you can use this to refer to member variables. That said, you'll often find that your code looks as follows in idiomatic C++:
class Blabla {
private:
int a_;
int b_;
public:
Blabla(int a, int b) : a_(a), b_(b) {}
};
As you can see, you normally do not apply the access control specifiers (public, protected or private) to each member, but you group them in sections.
Also, if you use the type of initialisation that you used above, the members get initialised twice - once with the default constructor when the object is created (basically, before the code inside the curly brackets is executed) and the second time during the assignments to this->a.
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