Re: Operator Overloading ==
coliban@gmail.com wrote:
i have a problem with Operator Overloading. I took the (standard)
example, Shape and the derived Classes Circle and Rectangle.
Using derivation in combination with a comparison operator is by far not
standard. The point is that this gets pretty complicated when the objects
are not of the same type; a simple approach would only compare the
baseclass elements and ignore the data of derived classes.
Anyway, I'll assume that you didn't use any polymorphism but just types with
plain value semantics.
In the Shape class, i defined an operator overloading (like in the
textbook found):
class Shape{
....
inline bool operator==( const Shape& lhs, const Shape& rhs) const {
cout << "NO" << endl;
return true;
}
....
}
Weird, that shouldn't have come from a textbook. The point is that there is
the object this is invoked on ('this') plus two more parameters used for a
binary operator which takes two parameters only. No, this is surely wrong;
there are two versions which work:
class Shape {
bool operator==(Shape const& rhs) const; // memberfunction
};
bool operator==(Shape const& lhs, Shape const& rhs); // (free) function
The difference is when using a memberfunction, you can only overload on the
right side of the comparison, not on the left. If you have e.g. a scalar
type you want to compare to a float, the only way to put the float on the
left is to use a free function.
Note that you can also write a friend function, then you can actually put it
inside the class definition, but it remains a non-member function! Oh, btw,
you can drop the 'inline' inside the class, it is implicit.
When i have two Objects, o1 and o2, both instantiated from Shape, i
thought, that i could compare them with the == Operator.
But when i try to compare them, it seems if the == Operator, which i
have defined (no "cout << "NO" " is happening) is not taken, rather
the compiler takes the build in comparator == and not my overloaded.
The compiler doesn't generate an operator==, so your analysis is wrong. I
guess that you are actually comparing pointers instead.
Uli
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]