0

Here is the code for which I am trying to understand the output.

class A
    {
    public:

        A();
        ~A(){ cout<<"Destructor Called from A"<<endl;}
        A(int x):Z(x){ cout<<"Constructor Called from A"<<endl; };

    private:
        int Z;
    };

    class B:public A
    {
    public:

        B();
        ~B(){ cout<<"Destructor Called from B"<<endl;}
        B(int x):A(x),Y(x){ cout<<"Constructor Called from B"<<endl; };

    private:
        int Y;
    };

    int main() {

        A *a = new B(10);        
        delete a;

        return 0;
    }

For which I get the output as

Constructor Called from A
Constructor Called from B
Destructor Called from A

My question is, what happened to destructor for class B? Is object slicing playing its part here?

Recker
  • 1,915
  • 25
  • 55

1 Answers1

5

You need to make the superclass's destructor virtual:

 class A {
    virtual ~A(){ cout<<"Destructor Called from A"<<endl;}
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151