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 background, where this was common. I am wondering if in C++ there are drawbacks doing the following (the code works):
class Player
{
public:
void setState(PlayerState *state)
{
this->state = state;
}
private:
PlayerState *state;
}
Thank you for the answers. As I understand while it works, a better practice would be to put some kind of marker to differentiate member variable from function parameters like:
_ or m_
In some editors (like Qt Designer), member variables are shows in a different color. This is why it did not seem necessary to add any prefixes.
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 whatm_stateis. It increases the readability of the code, and avoids common mistakes.Also, if
m_stateis the member, then you don’t have to writethis->m_state = statein the member function, you could just writem_state = state. In your current code,this->part becomes necessary, without whichstate = statewill become self-assignment.