I have a virtual class Element that forces its derived classes to have a == operator:
So, I have derived classes (Integer, Word) that implement that operator.
I have a class Group that basically is a list of elements.
In a function, I want to compare if an element from a group its equal to an element of a different group, so I’m using:
if(actual == lookingfor)
where both actual and lookingfor are pointers to Element…but the comparison is being made at the level of pointers, so both pointers are always different.
How can I force that the operator == from the derived class of element be used?
EDIT:
class Element
{
virtual int operator==(Elemento *)=0;
}
class Word : public Element { ... }
int Word::operator==(Element * element)
{
Element * ptr = element;
Word * wordPtr = dynamic_cast< Word * >(ptr);
int equal = 0;
if(wordPtr)
{
equal = strncmp(this->ptr,wordPtr->ptr,49)==0;
}
return igual;
}
please not that the below implementation uses references instead of pointers as arguments to
operator==defined as pure-abstract instruct Element. This is how it’s usually done and I’d recommend you to do the same in your code.It’s not possible to overload the comparision of pointers in
C++, you will have to dereference your pointers so that you’ll get valid objects which you can compare in a normal manner, and your ownoperator==will be called.Another method is to call your
operator==directly through your pointers, such as in the below example.