SimpleGuy SimpleGuy - 3 months ago 14
C++ Question

Including const in operator overloading argument list gives error (C++)

I am trying out with operator overloading, for which I wrote below code

class OwnClass
{
private:
int x,y;
public:
OwnClass(int x, int y) { SetX(x); SetY(y); }
int GetX() { return x; }
void SetX(int x) { this->x = x;}
int GetY() { return y; }
void SetY(int y) {this->y = y;}

OwnClass& operator + (const OwnClass &o) // Problematic line
{
this->x += o.GetX();
this->y += o.GetY();

return *this;
}
};


When compiled, following error is shown


fun.cpp(65): error C2662: 'OwnClass::GetX' : cannot convert 'this'
pointer from 'const OwnClass' to 'OwnClass &'
Conversion loses qualifiers

fun.cpp(66): error C2662: 'OwnClass::GetY' : cannot convert
'this' pointer from 'const OwnClass' to 'OwnClass &' Conversion loses
qualifiers


When I modify the code as under, it compiles fine.

OwnClass& operator + (OwnClass &o) // removed const
{
this->x += o.GetX();
this->y += o.GetY();

return *this;
}


I could not understand why so ? I mean I am not able to understand the compiler error.

Answer

The parameter o is declared as reference to const, which can't be called with GetX and GetY, because they're non-const member function. You can (and should) change them to const member functions to solve the issue.

int GetX() const { return x; }
int GetY() const { return y; }

BTW: In general binary operator+ is not supposed to return a reference to non-const. It's better to return a new object by value.

OwnClass operator + (const OwnClass &o)
{
    OwnClass r(GetX(), GetY());
    r.x += o.GetX();
    r.y += o.GetY();

    return r;
}