0

How should binary operator be overloaded,
CMyClass operator-(const CMyClass& oMyClass) const or
CMyClass operator-(const CMyClass& oMyClass)
What is the difference between both, Can the first call replace the second one completely.
I have found that using the second one only I wont be able to add const MyClass as LHS.

#include <iostream>
class CMyClass
{
    int m_y{ 0 };
    int m_x{ 0 };

public:
    CMyClass()
    {
    }

    CMyClass(int x, int y) :
        m_x{ x }, m_y{ y }
    {}

    CMyClass operator-(const CMyClass& oMyClass) const
    {
        CMyClass oReturn;
        oReturn.m_x = m_x - oMyClass.m_x;
        oReturn.m_y = m_y - oMyClass.m_y;
        return oReturn;
    }

    CMyClass operator-(const CMyClass& oMyClass)
    {
        CMyClass oReturn;
        oReturn.m_x = m_x - oMyClass.m_x;
        oReturn.m_y = m_y - oMyClass.m_y;
        return oReturn;
    }
};

int main()
{
    const CMyClass p1(10, 10);
    const CMyClass p2(5, 5);

    CMyClass p3 = p1 - p2;
    // ...
}
Kiran Thilak
  • 443
  • 5
  • 15
  • TL;DR `CMyClass operator-(const CMyClass& oMyClass)` looks like an odd overload. It shouldn't change `*this` so it should be `const` like every other function that doesn't change `*this`. Also, you can make it simpler by constructing `oReturn` using the copy constructor: `CMyClass oReturn(*this);` then add `operator-=` and call that: `oReturn -= oMyClass;`. – Ted Lyngmo Nov 30 '20 at 11:54
  • 2
    the question boils down to "What is a constant method?" and has not much to do with overloading. Better do one thing at a time. Do you know the difference between a `void CMyClass::foo()` and `void CMyClass::foo() const` ? – 463035818_is_not_an_ai Nov 30 '20 at 11:58

0 Answers0