Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Constructors can't be virtual.</p> <pre><code>class Shape { virtual ~Shape() = 0; }; class Circle : public Shape { Circle() {}; ~Circle() {}; }; int main() { Shape *s = new Circle(); delete s; } </code></pre> <p>Yes, <code>new Circle()</code> calls the constructor for Circle. This is because the expression <code>new &lt;type&gt;&lt;optional initializer&gt;</code> allocates memory sufficient for and then initializes it by calling the appropriate constructor (or other initialization for non-class types). Nothing about this needs to be virtual because you have explicitly states the most derived type.</p> <p>The result of <code>new Circle()</code> is a pointer to a Circle. Assigning this type to a variable of type pointer to Shape involves an implicit conversion. The result of the conversion is a pointer to the Circle's base Shape sub-object. Again, nothing about this is virtual, because the Shape is not a virtual base, it's just a regular base object and it's location inside the Circle is known statically.</p> <p><code>delete s</code> does call the Circle destructor. This does use virtual dispatch. The compiler knows it's deleting a Shape, and the destructor of Shape is virtual, so it looks up the appropriate destructor, which is <code>~Circle()</code>, and calls it. If Shape's destructor was not vitual (and actually had a definition somewhere) then this would not be done and only the Shape object would be destructed, not the Circle object, and the deallocation might not be done correctly. The behavior would be undefined.</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