Mr. Boy
Mr. Boy

Reputation: 63718

Equality operator that supports comparing two references to objects?

This is pre-existing code which works fine.

bool operator==(CMyClass X) {return m_Data==X.m_Data;}

if(a == b){...} //a and b are both CMyClass objects

But now I have code:

if(x.get() == y.get()){...} // get() returns CMyClass&

I already changed it to take a const reference

bool operator==(const CMyClass &X) {return m_Data==X.m_Data;}

And I still get the compile error:

error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const CMyClass' (or there is no acceptable conversion)

Do I need a simple amendment to my existing operator, or to add a new 2-arg version? Should equality operators not take const ref parameters as best practice anyway?

Upvotes: 0

Views: 281

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

An equality operator should take its parameter by const reference (since it won't be making any changes to the value), and also be a const function (if it is a class member).

So your declaration should be

bool operator==(const CMyClass &X) const {return m_Data==X.m_Data;}

Since your get function returns a const CMyClass &, your original equality comparison is uncallable since it is not a const function and can't be called on a const object.

Upvotes: 2

Related Questions