Search code examples
c++operator-overloadingoperand

Invalid operand error in overloaded operator


So I'm really confused about why I'm getting this invalid operand error. I have two classes, classA and ClassB. ClassB contains three ClassA pointers. The ClassA operator+= has been overloaded as follows:

ClassA& ClassA::operator+=(const ClassA& rhs)
{
    (*this).dataMem += rhs.dataMem;
    return *this;
}

And that works and everything. My problem comes in when I'm overloading the operator+= and operator+ in ClassB. The operator should just perform the + operation on the ClassA objects within it.

ClassB& ClassB::operator+=(const ClassB& rhs)
{
    (*this).mClassA + rhs.mClassA;
    return *this;
}

I am confused because I have overloaded other operators in ClassB using the exact same format and calls, but I am only receiving the invalid operand error while overloading the + and += operator.

This is the error that I'm receiving: ClassB.cpp:93: error: invalid operands of types ClassA* and ClassA* const to binary operator+.

Any sort of help or suggestions would be greatly appreciated. Thanks!


Solution

  • void ClassB::operator+=(const ClassB& rhs)
    {
        (*this).mClassA + rhs.mClassA;
    }
    

    This function accepts an argument of type ClassB, so operator + of ClassA will not be called when you call this modify it to

    void ClassB::operator+=(const ClassA& rhs)
    {
        (*this).mClassA + rhs.mClassA;
    }
    

    and it will work