This question already has answers here:
Closed 6 years ago.
For example, is this any of the following
- Bad practice
- Unreadable
- Inefficient (the call to
this
pointer)
- Any other reason why it's bad to do this
.
class Person {
public:
string name;
Person(string name) {
this->name = name;
}
};
P.S.
How about Person(string name) : name(name) { }
The only issue(not a real issue) I can think of is that you can't distinguish member variable
with local variable
or function parameter
. It's just coding style, it's nothing to do with efficiency, but when you talk about Unreadable
, that's yes for me.
For me I normally name class member variable with trailing underscore. It helps code readability and makes it easier for maintenance.
class Person {
public:
string name_; // member variable with traling `_`
string m_surname; // some microsoft style declares member start with `m_`
Person(const string& name) // pass parameter by reference.
: name_(name) // you know you are constructing member name_ with name variable
{
}
};
No, I don't think this is a bad way to do so. Sometimes we even face the same method name or property name from different libraries. That's why we create namespace and class to resolve the naming conflict.
As long as it will not result in confusion, you should make it as simple as possible. Even though they use the same name. However, you shouldn't mix them, for example:
class Person {
public:
Person(name) {
this->name = name;
name = clean(this->name);
this->name = prefix + name;
}
private:
string name;
};
Keep it clean:
class Person {
public:
Person(name) {
name = clean(name);
name = prefix + name;
this->name = name;
}
private:
string name;
};