Question

In C++ we can use assignment in a constructor to initialize the object, or we can use an initializer list. For const data members, or data members which are objects, the initializer list is the only way. However, when the name of the parameter matches the name of the data member, this->name(name) does not work. Is there any way to do this if the names are the same?

class A {
private:
  int _x,y;
public:
  A(int x, int y) : _x(x), // this works
   this->y(y) // this does not work
  {}
};

I thought that perhaps this is an order of operation problem so I tried:

(this->y)(y)

but that isn't right either.

Was it helpful?

Solution

You just use the constructor initialization list:

  A(int x, int y) : _x(x), y(y) {}

There is no reason to involve this here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top