Coming from Java
, I am used to doing this:
void setColor(String color) {
this.color = color;
}
However, I recently switched to C++
, and I see a lot of this instead:
void setColor(string c) {
color = c;
}
Why not this? Is this not recommended?
void setColor(string color) {
this->color = color;
}
It's the exact same thing. In Java if you had named your parameter c
instead of color
, you would not have any shadowing and you could easily write
void setColor(String c) {
color = c;
}
The this
in Java (or C++ for that matter) is only needed to specify exactly which color
you are referring to: the member variable or the local variable.
There is no need to use this
, because there is no conflict between local and member variable and no fields are hidden. Generally you don't want this conflict to happen at all by not having same variable as an constructor parameter and also as local variable (despite so many books teach you exactly this).
I find this is much more smooth(and also more readable even if you don't have background from particular language):
private String localColor;
void setColor(String color) {
localColor = color;
}
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