Can someone ask to lead me out of my misery with this? I am trying to understand why the derived operator == is never called in a loop. To simplify the example, here is my Base and Derived class:
class Base { // ... snipped bool operator==( const Base& other ) const { return name_ == other.name_; } }; class Derived : public Base { // ... snipped bool operator==( const Derived& other ) const { return ( static_cast<const Base&>( *this ) == static_cast<const Base&>( other ) ? age_ == other.age_ : false ); };
Now when I instantiate and compare this ...
Derived p1("Sarah", 42); Derived p2("Sarah", 42); bool z = ( p1 == p2 );
... everything is fine. The == operator from Derived is called here, but when I iterate over the list, comparing the items in the list of pointers to Base objects ...
list<Base*> coll; coll.push_back( new Base("fred") ); coll.push_back( new Derived("sarah", 42) ); // ... snipped // Get two items from the list. Base& obj1 = **itr; Base& obj2 = **itr2; cout << obj1.asString() << " " << ( ( obj1 == obj2 ) ? "==" : "!=" ) << " " << obj2.asString() << endl;
Here, asString() (which is virtual and not shown here for brevity) works fine, but obj1 == obj2 always calls Base operator== , even if both are Derived objects.
I know that I am going to kick myself when I find out what is wrong, but if someone can softly let me down, it will be very grateful.
source share