Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The abstract base class cannot help in case of assignment because the base sub-object is not instantiated (what an abstract class would block) but is sliced off the derived object (i.e. the assignment is done between already existing base sub-objects).</p> <p>To avoid the problem the only solution I can think to is</p> <ol> <li>make the assignment virtual</li> <li>check in the assignment that the source instance is of the correct type</li> </ol> <p>In code</p> <pre><code>#include &lt;iostream&gt; struct Base { int bx; Base(int bx) : bx(bx) {} virtual Base&amp; operator=(const Base&amp; other) { bx = other.bx; return *this; } }; struct A : Base { int x; A(int bx, int x) : Base(bx), x(x) {} A&amp; operator=(const Base&amp; other) { const A&amp; other_a = dynamic_cast&lt;const A&amp;&gt;(other); Base::operator=(other); x = other_a.x; return *this; } }; struct B : Base { int x; B(int bx, int x) : Base(bx), x(x) {} B&amp; operator=(const Base&amp; other) { const B&amp; other_b = dynamic_cast&lt;const B&amp;&gt;(other); Base::operator=(other); x = other_b.x; return *this; } }; </code></pre> <p>The <code>dynamic_cast&lt;const A&amp;&gt;(other)</code> is the operation that will fail if the object passed to the assignment operator is not of the correct derived type (it can be a sub-derived object, but this should be logically ok for an assignment <strong>source</strong>).</p> <p>As an example:</p> <pre><code>int main(int argc, const char *argv[]) { Base *pa1 = new A(1, 2); Base *pa2 = new A(3, 4); Base *pb1 = new B(5, 6); Base *pb2 = new B(7, 8); *pa1 = *pa2; std::cout &lt;&lt; pa1-&gt;bx &lt;&lt; "/" &lt;&lt; dynamic_cast&lt;A*&gt;(pa1)-&gt;x &lt;&lt; "\n"; *pb1 = *pb2; std::cout &lt;&lt; pb1-&gt;bx &lt;&lt; "/" &lt;&lt; dynamic_cast&lt;B*&gt;(pb1)-&gt;x &lt;&lt; "\n"; std::cout &lt;&lt; "Ok so far\n"; *pa1 = *pb1; // Runtime error here (bad cast) return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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