Search code examples
c++instance-variables

How can I assign to an instance variable in C++ when a local variable has same name?


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; }