Reputation: 17334
Can a C++ class member function's argument have the same identifier (name) as a member data of the same class?
My method for dealing with this was to use the this
pointer, however I am not sure the code will compile as expected;
For example:
class M {
[public/private:]
int i;
void add(int i)
{
(this->i) = ((this->i) + i);
return;
}
}
Quite a strange example, but it demonstrates the principle. Are the parentheses required?
Upvotes: 0
Views: 890
Reputation: 73542
As Jarod42 told you, the code is valid without parentheses.
An alternative way, not using this
is to use scope resolution operator ::
:
class M {
public:
int i=0; // better initialize it, if you do not have a constructor.
void add(int i)
{
M::i = M::i + i; // the i belonging to class M vs. parameter i
return;
}
};
Upvotes: 2
Reputation: 2702
your code is correct, but you could just use:
void add(int i) {
this->i += i;
}
as you don't need parenthesis, also the +=
doesn't make it look so ugly. And btw: you don't need an explicit return statement as the method returns upon completion automatically.
Upvotes: 1
Reputation: 218238
The code is valid, and parentheses are not required.
In addition, you may also have
class M
{
public:
explicit M(int i) : i(i) {} // initialize member with method argument as expected.
private:
int i;
};
Upvotes: 1
Reputation: 27538
however I am not sure the code will compile as expected;
Why don't you just try it?
Anyway, the answer is: yes, it will.
It's just that if you run into this problem very often, chances are that your identifiers could be longer or more descriptive. i
is hardly an acceptable name for a function parameter or member variable.
You will also find that many coding standards require you to distinguish member variables from function parameters, e.g. by prepending all member variables with m_
. In that case, your i
member variable would become m_i
. These are stylistic issues, with the potential of creating heated discussions.
The parentheses in your example are redundant. Sometimes, redundant parentheses enhance readability of code, but in this case I don't think so. And of course, using the +=
operator further simplifies the code:
void add(int i)
{
this->i += i;
return;
}
Upvotes: 0