Click here to Skip to main content
15,890,670 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, Actually am trying to learn the virtual concept but the thing is how it was working while adding the virtual keyword in class destructor.

class A
{
   public:
      int a1;
      int b1;

      A()   {  cout<<"A's Constructor\n"; }

      virtual void foo()
      {
         cout<<"Base : foo\n";
      }

      //~A()  {  cout<<"A's Destructor\n";  }
      virtual ~A()  {  cout<<"A's Destructor\n";  }
};

class B : public A
{
   public:
      B()   {  cout<<"B's Constructor\n"; }

      void foo()
      {
         cout<<"Dervied : foo\n";
      }

      ~B()  {  cout<<"B's Destructor\n";  }
};

int main()
{
   A* a1 = new A();
   cout<<"------------------Another------------------\n";
   A* a2 = new B();
   cout<<"------------------Another------------------\n";
   B* b1 = new B();
   cout<<"------------------D-->a1  Another------------------\n";
   delete a1;
   cout<<"------------------D-->a2  Another------------------\n";
   delete a2;
   cout<<"------------------D-->b1  Another------------------\n";
   delete b1;
}


How, delete of a2 object calls the destructor???

What I have tried:

Trying to learn the concept of destructor seen the v-table flow control
Posted
Comments
mathiv327 10-Oct-23 9:12am    
How, if it is not vitual calls only the base destructor.
else virtual calls the both destructor.

1 solution

Because polymorphism works that way. See, for instance: C++ Polymorphism[^].
 
Share this answer
 
Comments
mathiv327 10-Oct-23 13:18pm    
How, with virtual it calls the both base and derived class destructor.
But without destructor calls only base class destructor.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900