Note that there are some explanatory texts on larger screens.

plurals
  1. POOperator== in derived class never gets called
    text
    copied!<p>Can someone <i>please</i> put me out of my misery with this? I'm trying to figure out why a derived operator== never gets called in a loop. To simplify the example, here's my Base and Derived class:</p> <pre><code>class Base { // ... snipped bool operator==( const Base&amp; other ) const { return name_ == other.name_; } }; class Derived : public Base { // ... snipped bool operator==( const Derived&amp; other ) const { return ( static_cast&lt;const Base&amp;&gt;( *this ) == static_cast&lt;const Base&amp;&gt;( other ) ? age_ == other.age_ : false ); }; </code></pre> <p>Now when I instantiate and compare like this ...</p> <pre><code>Derived p1("Sarah", 42); Derived p2("Sarah", 42); bool z = ( p1 == p2 ); </code></pre> <p>... all is fine. Here the operator== from Derived gets called, but when I loop over a list, comparing items in a list of pointers to Base objects ...</p> <pre><code>list&lt;Base*&gt; coll; coll.push_back( new Base("fred") ); coll.push_back( new Derived("sarah", 42) ); // ... snipped // Get two items from the list. Base&amp; obj1 = **itr; Base&amp; obj2 = **itr2; cout &lt;&lt; obj1.asString() &lt;&lt; " " &lt;&lt; ( ( obj1 == obj2 ) ? "==" : "!=" ) &lt;&lt; " " &lt;&lt; obj2.asString() &lt;&lt; endl; </code></pre> <p>Here <code>asString()</code> (which is virtual and not shown here for brevity) works fine, but <code>obj1 == obj2</code> <i>always</i> calls the <code>Base</code> <code>operator==</code> even if the two objects are <code>Derived</code>.</p> <p>I know I'm going to kick myself when I find out what's wrong, but if someone could let me down gently it would be much appreciated.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload