Is it bad to have the same name for parameter as for member variable? [duplicate]

陌路散爱 提交于 2019-12-01 04:16:19

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;
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!