Should I use the same name for a member variable and a function parameter in C++?

前端 未结 9 1793
自闭症患者
自闭症患者 2020-12-08 03:08

I am wondering if it is a good practice to use the same name for both a member variable and a function parameter in C++.

I come from a Java backgro

相关标签:
9条回答
  • 2020-12-08 03:47

    That is correct, and allowed by the Standard. But a better approach is to use some naming-convention for member variables. For example, you could use m_ prefix for all member variables, then anyone could infer what m_state is. It increases the readability of the code, and avoids common mistakes.

    Also, if m_state is the member, then you don't have to write this->m_state = state in the member function, you could just write m_state = state. In your current code, this-> part becomes necessary, without which state = state will become self-assignment.

    0 讨论(0)
  • 2020-12-08 03:51

    Please note that some compilers (vs 2015) may generate a warning if a variable shadows another. Off course, one can disable these kind of warnings. But I think it is good practice to have these checks enabled.

    0 讨论(0)
  • 2020-12-08 03:57

    I find it a good choice to give member variables the same name as constructor initialization parameters.

    Here are my reasons:

    • reduces the number of identifiers, hence reduces the complexity
    • you don't need to invent so many identifiers
    • same things should have same name if possible, that is logically speaking, I know
      parameter != member
    • contexts and indices can allow to give the same name to the same thing
    • you more easily find references (identifiers) to the logical thing by searching, if all references have the same name
    0 讨论(0)
提交回复
热议问题