Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setters and getters in C++

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;
}
like image 973
user1529412 Avatar asked Oct 28 '15 16:10

user1529412


2 Answers

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.

like image 165
NoseKnowsAll Avatar answered Sep 21 '22 22:09

NoseKnowsAll


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;
}
like image 42
The Law Avatar answered Sep 19 '22 22:09

The Law