Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 260
Anton Avatar asked Apr 20 '12 16:04

Anton


People also ask

Can a function and variable have the same name in C?

You cant because if you have example(), 'example' is a pointer to that function. This is the right answer. There are function pointers, which are variables. But also, all function names are treated as const function pointers!

Can parameter have same name as variable?

Although it is usually a bad idea, you can declare a formal parameter or a local variable with the same name as one of the instance variables.

Do parameters and arguments have to have the same name?

The caller's arguments passed to the function's parameters do not have to have the same names.

What happens if parameter name is same as variable name?

Answer. When a parameter has the same name as a variable defined outside, instead of the function using the variable defined outside, it will only reference the value that was passed to the parameter. So, parameters will be used over variables of the same name within a function.


2 Answers

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.

like image 67
Nawaz Avatar answered Sep 23 '22 07:09

Nawaz


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.

like image 31
111111 Avatar answered Sep 22 '22 07:09

111111