Here is a very simple class hierarchy:
class A { public: A( int _a ) : a( _a ) {} virtual bool operator==( const A& right ) const { return a == right.a; } virtual bool operator!=( const A& right ) const { return !( *this == right ); } int a; }; class B : public A { public: B( int _a, int _b ) : A( _a ), b( _b ) {} virtual bool operator==( const B& right ) const { return A::operator==( right ) && b == right.b; } int b; };
As you can see, the! = Operator is defined in the base class. Since I am very lazy, I do not want to duplicate such simple code in all derived classes.
Unfortunatley, with this code:
A a4(4), a5(5), a4bis(4); assert( a4 == a4bis ); assert( a4 != a5 ); B b1(4,5), b2(4,6); assert( !(b1 == b2) ); assert( b1 != b2 );
b1 != b2 returns false because it executes A::operator!= , which calls A::operator== , not B::operator== (even if the operator is virtual, since the version parameter of the derived class is different, they not related in vtable).
So what's the best way to address? = operator in the general case for a class hierarchy?
One solution is to repeat it in each class, B will have:
virtual bool operator!=( const B& right ) const { return !( *this == right ); }
But itβs a pain when you have a lot of activities .... I have 30 ....
Another solution would be to have a generic template approach:
template <class T> bool operator!=( const T& left, const T& right ) { return !( left == right ); }
But this bypasses any operator != Defined by any class .... so it can be risky if you declare it differently (or if you declare == itself calling != ), It will end up with an infinite loop .. .). Therefore, I believe that this solution is very dangerous ... except that we can restrict the template that will be used for all classes derived from the class of our top-level hierarchy ( A in my example) .... but I donβt think It is doable at all.
Note. I do not use C ++ 11, but ... sorry.