-3

I'm having a hard time figuring out how this destructor call

So I have class A with virtual destructor and inline virtual clone function

class A{
public:
    A(){ }
    virtual ~A(){
        qDebug() << "Class A destructor";
    }

    inline virtual A *clone(){
        return NULL;
    }
};

Then I have sub-class B also have destructor and clone function return pointer to class A

class B : public A{
public:
    B() { }
    ~B(){
        qDebug() << "Class B destructor";
    }
    A *clone(){
        B *temp = new B();
        return static_cast<A *>(temp);
    }
};

And I have main function and test function and i start do some crazy thing about pointer

A *test(A *input){
    return input->clone();
}

int main(){

    B temp2;
    A *temp = test(&temp2);
    delete temp;

    return 0;
}

Finally if I have the output is

Class B destructor
Class A destructor
Class B destructor
Class A destructor

and if I'm not using virtual before destructor class A, I have ouput is

Class A destructor
Class B destructor
Class A destructor

So can anyone explain me why virtual make so much different

BulletRain
  • 92
  • 9
  • This has nothing to do with the clone function. Make a main function that contains only `A* x = new B(); delete x;` and see what happens with and without virtual destructor. – pschill Jun 12 '18 at 09:49
  • https://stackoverflow.com/questions/1306778/c-virtual-pure-virtual-explained https://stackoverflow.com/questions/461203/when-to-use-virtual-destructors – Piotr Siupa Jun 12 '18 at 09:50
  • `delete temp;` where dynamic type of temp is `B*` whereas static type is `A*` with non virtual destructor is UB. – Jarod42 Jun 12 '18 at 09:55

1 Answers1

0

When to use virtual destructors?

In few words: without virtual there is no vTable and at runtime it is impossible to find derived destructor when you call one of a base class.