Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you instrument the code you will see that when you call <code>Derived d2(d1)</code> the Derived::Derived(Base&amp;) constructor is not being called. This is because the d1 argument is a better match for the implicit copy constructor, which just copies the b member from d1 to d2.</p> <p>In order to see the behavior you expect, you can explicitly cast the d1 to <code>(Base&amp;)d1</code>. If you do so you will get code like the following (with the instrumentation):</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; class Base { public: Base() {} virtual ~Base() {} virtual std::string text() const { return "Base"; } }; class Derived: public Base { public: Derived(Base&amp; _b): b(_b) {std::cout &lt;&lt; "init'ed with: " &lt;&lt; _b.text() &lt;&lt; std::endl;} virtual ~Derived() {} virtual std::string text() const { return b.text() + " - Derived"; } private: Base&amp; b; }; int main(int argc, char const *argv[]) { std::cout &lt;&lt; "Creating Base" &lt;&lt; std::endl; Base b; std::cout &lt;&lt; "Creating d1" &lt;&lt; std::endl; Derived d1(b); std::cout &lt;&lt; d1.text() &lt;&lt; std::endl; std::cout &lt;&lt; "Creating d2" &lt;&lt; std::endl; Derived d2(d1); std::cout &lt;&lt; d2.text() &lt;&lt; std::endl; std::cout &lt;&lt; "Creating d3" &lt;&lt; std::endl; Derived d3((Base&amp;)d1); std::cout &lt;&lt; d3.text() &lt;&lt; std::endl; return 0; } </code></pre> <p>And this gives the expected output:</p> <pre><code>Creating Base Creating d1 init'ed with: Base Base - Derived Creating d2 Base - Derived Creating d3 init'ed with: Base - Derived Base - Derived - Derived </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.
 

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