0

Here i am faced with problem in destructor of objects. In the program given below i am trying to make object with the base class pointer dynamically and when i am trying delete that pointer than pointer just delete object of A. So how can i delete all the objects at the end of program?

class A{
         public:
            A(){
            cout<<"Object A is created "<<endl;
            }
            ~A(){
             cout<<"Object A is destroyed"<<endl;
             }
       };
class B{
        public:
          B(){
          cout<<"object B is Created \n";
          }
          ~B(){
           cout<<"Object B is Destroyed"<<endl;
           }
       };
class C{
        public:
          C(){
          cout<<"constructor of C class"<<endl;
          }
          ~C(){
           cout<<"destructor of C "<<endl;
           }
       };
class D:public C, public B, public A{
     public:
       D(){
       cout<<"Object D is created "<<endl;
       }
       ~D(){
        cout<<"Object D is destroyed "<<endl;
        }
  };
int main()
{
   A *a;
   a = new D();
   delete a;
   return 0;
}

1 Answers1

1

Declare the destructors of base classes as virtual.

Do read this for why.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79