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
Normally people just put an underscore after the variable or use shorter less descriptive var names for the function parameter.
I personally do not like the same name thing because when reading it, it is easy to make mistakes.
This is more a style issue than anything else. Most of the time,
there's no issue: state
is a very poor name for a variable or a value,
as variables and values should be qualified nouns, e.g.:
void setState( PlayerState* newState )
{
currentState = newState;
}
In theory, anyway. In practice, I've found it useful to use prefixes, along the lines of:
class Player
{
PlayerState* myState;
public:
void setState( PlayerState* newState )
{
myState = newState;
}
};
When reading the code, if the name starts with my
, it's clearly a
member variable (and if it starts with our
, it's a static member
variable).
Note too that in the constructor, you can do things like:
Player::Player( PlayerState* state )
: state( state )
{
}
I'm not sure what this does for readability, however:
Player::Player( PlayerState* initialState )
: myState( initialState )
{
}
looks a lot clearer (but for simple data holders, the distinction might not be so significant).
Do it this way:
class Player
{
public:
void setState(PlayerState *state)
{
this->m_state = state;
}
private:
PlayerState *m_state;
}
You'll thank me some time later on. Haha.. (:
The "m_" ("Member") prefix distinguish members from functions and other stuff. Very useful with stuff like intellisense (or any other IDE auto-suggestion).
Also, mark m_state
as const
if you do not intend to change it later. Just in case.
There is not really any difference between the C++ and Java, the only drawback is that you have to type this->state = state
instead of state = arg
.
But your code is perfectly acceptable, it's more of styling than anything else.
I would suggest you to follow some coding style convention. Personally I use the:
class Player
{
public:
void setState(PlayerState *state)
{
_state = state;
}
private:
PlayerState* _state;
}
It's fine, in-fact it might even be good form, so long as it's only ever in your constructor.