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
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).