For example, is this any of the following
this
pointer).
class Person {
public:
string name;
Person(string name) {
this->name = name;
}
};
P.S.
How about Person(string name) : name(name) { }
Although it is usually a bad idea, you can declare a formal parameter or a local variable with the same name as one of the instance variables.
Answer. When a parameter has the same name as a variable defined outside, instead of the function using the variable defined outside, it will only reference the value that was passed to the parameter. So, parameters will be used over variables of the same name within a function.
Yes, the names of the variables you pass in a function call can be the same as the names of the parameters in the function definition.
No, it is not. Because they both are in different scope. x outside of main function has class level scope while x inside of main has method/function level scope. It is legal for 2 variables in different scope to have same name.
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;
};
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
{
}
};
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