Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A virtual constructor is not possible but virtual destructor is possible. Let us experiment....</p> <pre><code>#include &lt;iostream&gt; using namespace std; class Base { public: Base(){ cout &lt;&lt; "Base Constructor Called\n"; } ~Base(){ cout &lt;&lt; "Base Destructor called\n"; } }; class Derived1: public Base { public: Derived1(){ cout &lt;&lt; "Derived constructor called\n"; } ~Derived1(){ cout &lt;&lt; "Derived destructor called\n"; } }; int main() { Base *b = new Derived1(); delete b; } </code></pre> <p>The above code output the following:</p> <pre class="lang-none prettyprint-override"><code>Base Constructor Called Derived constructor called Base Destructor called </code></pre> <p>The construction of derived object follow the construction rule but when we delete the "b" pointer(base pointer) we have found that only the base destructor is call.But this must not be happened. To do the appropriate thing we have to make the base destructor virtual. Now let see what happen in the following:</p> <pre><code>#include &lt;iostream&gt; using namespace std; class Base { public: Base(){ cout &lt;&lt; "Base Constructor Called\n"; } virtual ~Base(){ cout &lt;&lt; "Base Destructor called\n"; } }; class Derived1: public Base { public: Derived1(){ cout &lt;&lt; "Derived constructor called\n"; } ~Derived1(){ cout &lt;&lt; "Derived destructor called\n"; } }; int main() { Base *b = new Derived1(); delete b; } </code></pre> <p>The output changed as following:</p> <pre class="lang-none prettyprint-override"><code>Base Constructor Called Derived constructor called Derived destructor called Base Destructor called </code></pre> <p>So the destruction of base pointer(which take an allocation on derived object!) follow the destruction rule i.e first the derived then the base. On the other hand for constructor there are nothing like virtual constructor.</p>
    singulars
    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.
    3. 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