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.