How can I assign to an instance variable in C++ when a local variable has same name?
-
25-09-2019 - |
Question
I have a class defined like this:
class MyClass
{
int x;
public:
MyClass(int x);
};
MyClass::MyClass(int x)
{ //Assign x here
}
However, I can't initialize x
in the constructor because it has the same name as an instance variable. Is there any way around this(other than changing the name of the argument)?
Solution
The best option is to use the constructor's initializer list:
MyClass::MyClass(int x) : x( x ) { // Body }
But you could also try this approach:
MyClass::MyClass(int x) { this->x = x; }
OTHER TIPS
However, I can't initialize x in the constructor because it has the same name as an instance variable. Is there any way around this(other than changing the name of the argument)?
So change the name of the parameter!
class MyClass
{
int x;
public:
MyClass(int xInitVal);
};
MyClass::MyClass(int xInitVal)
:x(xInitVal)
{ // Don't assign x here.
}
By makeing the parameter name the same as a local you are just making the code hard to read. Don't do it. Nearly every style guide you come across will tell you not to make parameters the same name as members. A small bit of common sense please.
<rant> To all the people that answered:
this->x = x;
Don't ask me for a job. My god are you delibrately trying to cause problems.
The fact that it looks horrible is not a give away that this is a bad idea.
Yes it is techncially allowed but the whole point is to make code easy to read and maintain not try and make it an exotic art of decoding the intentions of the previous author.
</rant>
as an aside - you really should have a naming convention for your member variables that does not clash. This is usually coding rules 1 or 2 for c++ houses. Then when you see m_foo = bar you know exactly what is going on
we use
int m_thingy;
I have also seen
int _thingy;
int thingy_
apologies in advance if you knew this and could not or would not do it
this->x = x;
You can use this
to explicitly refer to the current object:
this->x = x;
I strongly recommend you just change the variable names. Messing with duplicate identifiers is a fight without a cause.
In my code, I give all function parameters the prefix 'in' ("inValue"). I give all private member variables the prefix 'm' ("mValue").
Use this->x
instead.
Use the this pointer
MyClass::MyClass(int x)
{
this->x = x;
}
Of course not having colliding names like that in the first place would be a better solution.
this->x = x isn't working? That's what we did (or used a different parameter name).