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>