vendredi 4 août 2017

When I use dynamic_cast and delete the object delete , how the destructor works?

I create a object of derived class and a base class point for it , and then I use the dynamic_cast convert base class point to derived class point . I delete the derived class point , but the program calls the derived destructor and the base destructor. Why does the program call the base destructor? After all, the base destructor isn't a virtual function....

#include<iostream>
#include<stdlib.h>
using namespace std;


class con {
private:
    double num;
public:
    con() {
        num = 0;
        cout << "default..." << endl;

    }
    void getnum() {
        cout << num << endl;
    }
};




class base {
public:
    virtual void A() {
        cout << "it is base A" << endl;
    }

    void B() {
        cout << "it is base B" << endl;
    }

    ~base() {
        cout << "it is base decon" << endl;
    }
};


class child : public base {
public:
    void A() {
        cout << "it is child A" << endl;
    }

    void B() {
        cout << "it is child B" << endl;
    }

    ~child() {
        cout << "it is child decon" << endl;
    }

};


int main(int argc, char** argv) {

    base* b = new child();
    child* c = dynamic_cast<child*>(b);
    delete c; //the program print "it is child decon"   "it is base decon"
    getchar();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire