Curtis2
Curtis2

Reputation: 116

Can I only have const overloaded operator member function?

I'm implementing a fraction class, and need to overload arithmetic operators. The problem is, can I only implement a const version.

For example, addition:

Fraction operator+( const Fraction& other ) const;

Since both non-const, and const Fraction objects can call this function, do I still need to have an non-const operator+ member function?

Upvotes: 1

Views: 141

Answers (3)

Pete Becker
Pete Becker

Reputation: 76315

In general, this kind of problem is better solved with a member operator+= and a nonmember operator+, like this:

class Fraction {
public:
    const Fraction& operator+=(const Fraction&);
};

Fraction operator+(const Fraction& lhs, const Fraction& rhs) {
    Fraction res(lhs);
    res += rhs;
    return res;
}

Upvotes: 4

Matteo Italia
Matteo Italia

Reputation: 126807

No. You can call const methods over non-const objects, exactly as you can have const references bind to non-const objects. IOW, you can always pass an object that you can modify to code that promises not to modify it - there's no loss of safety. The opposite of course is not true - if you have a const object (=> an object you promised not to modify) you cannot pass it to code that doesn't adhere to this promise.

Upvotes: 3

juanchopanza
juanchopanza

Reputation: 227418

const member functions can be called on non-const objects, so no, you don't need a non-const overload.

Fraction a, b;
Fraction c = a + b; // no problem

Upvotes: 4

Related Questions