Reputation: 142
I am currently implementing classes for labeling support in c++. However, I am a bit confused about the different behaviour of the overloaded operator and isEqual methods:
class Lbl
{
public:
virtual bool operator == (const Lbl* l) const = 0;
virtual bool isEqual (const Lbl* l) const = 0;
};
class SubLbl : public Lbl
{
public:
SubLbl(){}
bool operator == (const Lbl* l) const {return true;}
bool isEqual (const Lbl* l) const {return true;}
};
int main(int argc, char** argv) {
SubLbl* l1 = new SubLbl();
SubLbl* l2 = new SubLbl();
cout << (l1 == l2) << endl;
cout << (l1->isEqual(l2)) << endl;
return 0;
}
Output:
0
1
Why is this? How do I need to change this to get the operator overloaded as well? Why do I have to inherit "public" to have the "isEqual" method be accessable? Or is this just a typical situation for templates which I have not used (and do not know) so far?
What I am doing is implementing different SubLbl classes for the support of different type of labels I can put on objects. All (SubLbl classes) inherit from the Lbl class and should overload the equality operator due to their own equality definitions (int comparison is different to the comparison of two complex objects and even different to a double comparison). Later (in the program) I do not want to know what kind of sub-label I am currently looking at, I just want to know whether they are equal or not.
Upvotes: 1
Views: 224
Reputation: 20336
I have to say, reading better, it's a pretty tricky answer, because you are speaking about inheritance and overloading an operator.
My guess is that you shouldn't compare objects with operator== if you don't know they are exactly the same kind of class. I thing you should only define, within SubLbl:
bool operator == (const SubLbl& l) const {return _something_;}
Note I put an object of type SubLbl as argument. And I would avoid defining a virtual operator==
in Lbl, especially if virtual.
The function isEqual, on the other hand, could be ok.
You can find some inspiration for different solutions here: Making operator<< virtual?
This is my old answer
In the first case, you are not calling the operator you defined, but you are checking if the 2 pointers point to the same object, or better, have the same value.
To call your operator, you should have put:
cout << (*l1 == l2) << endl;
But the way you defined the operator is not recommendable. You should, for example, define:
bool operator == (const Lbl& l) const {return _something_;}
and call
cout << (*l1 == *l2) << endl;
Upvotes: 1
Reputation: 227628
This one:
l1 == l2
is comparing pointers. This will ony be true if the addresses of l1
and l2
ar ethe same.
This one
l1->isEqual(l2)
is performing a calling a member function that returns true
.
Upvotes: 1