Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>A a = *(A *)new B(); a.func(); </code></pre> <p>Here's what happens in this code, step by step:</p> <ul> <li><code>new B()</code>: a new object of type B is allocated on the free store, resulting in its address</li> <li><code>(A*)</code>: the address of the object is cast to <code>A*</code>, so we have a pointer of type <code>A*</code> actually pointing to an object of type B, which is valid. All OK.</li> <li><code>A a</code>: here the problems start. A new <strong>local object</strong> of type A is created on the stack and constructed using the copy constructor <code>A::A(const A&amp;)</code>, with the first paremeter being the object created before.</li> <li>The pointer to the original object of type B is lost after this statement, resulting in a memory leak, since it was allocated on the free store with <code>new</code>.</li> <li><code>a.func()</code> - the method is called on the (local) object of class A.</li> </ul> <p>If you change the code to:</p> <pre><code>A&amp; a = *( A*) new B(); a.func(); </code></pre> <p>then only one object will be constructed, its pointer will be converted to pointer of type <code>A*</code>, then dereferenced and a new <strong>reference will be initialized with this address</strong>. The call of the virtual function will then be dynamically resolved to <code>B::func()</code>.</p> <hr> <p>But remember, that you'd still need to free the object since it was allocated with <code>new</code>:</p> <pre><code>delete &amp;a; </code></pre> <p>Which, by the way, will only be correct if A has a virtual destructor, which is required that B::~B() (which luckily is empty here, but it doesn't need to in the general case) will also be called. If A doesn't have a virtual destructor, then you'd need to free it by:</p> <pre><code>delete (B*)&amp;a; </code></pre> <hr> <p>If you would want to use a pointer, then that's the same as with the reference. Code:</p> <pre><code>A* a = new B(); // actually you don't need an explicit cast here. a-&gt;func(); delete (B*)a; // or just delete a; if A has a virtual destructor. </code></pre>
 

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