Search code examples
c++operatorsoperator-overloading

How to return first operand if the second operand of + operator overloading is zero in C++?


I have this class definition:

class foo{

public:
    foo();
    foo(const int& var);
    foo(const foo& var);
    ~foo();

    const foo operator +(const foo& secondOp) const;

private:
    int a;
    //plus other values, pointers, e.t.c.

};

Also I have made this implementation for '+' operator overloading:

const foo foo::operator +(const foo& secondOp) const{

    //I want here to check if i have one operand or two...
    if ((FIRST_OPERAND.a!=0) && (secondOp.a==0)){
        cout << "ERROR, second operand is zero";
        return FIRST_OPERAND;
    }
    else if ((FIRST_OPERAND.a==0) && (secondOp.a!=0)){
        cout << "ERROR, first operand is zero";
        return secondOp;
    }

}

When i write in main():

foo a(2);
foo b;
foo c;

//I want here to print the ERROR and
//return only the values of a
c = a + b;
  1. Ηow can i return the value of the first operand if the second operand is zero and vice versa?

Solution

  • You're almost there. Since it's a member function, the first operand is *this, so replace FIRST_OPERAND.a with this->a or just a.

    However, it might be better to make it a non-member function to allow conversions on both operands (i.e. to be able to write a + 2 or 2 + a). It will need to be a friend in order to access the private member(s).

    friend foo operator +(const foo& firstOp, const foo& secondOp);
    

    Also, it's best not to return a const value as that prevents moving from the return value.