Destructor virtual and non-virtual

http://www.cppblog.com/aaxron/archive/2010/12/23/137293.html
Once the inheritance mechanism used, if the base class virtual function is not set, then the destructor is subclass may be called .
Why is possible and not necessarily do?
because it is only in the hands of the scene;

class Base
{
public:
    Base(){
        cout<<"Base Construcing"<<endl;
    }

    ~Base(){
        cout<<"Base Destrucing"<<endl;
    }

};

class Derived : public Base
{
public:
    Derived(){
        cout<<"Derived Constructing"<<endl;
    }

    ~Derived(){
        cout<<"Derived Destructing"<<endl;
    }
};

int main() {
    Base *base = new Derived;
    delete base;

cout<< "*************分割线*************"<<endl;
    Derived Derived;
    return 0;
}

Here is the output

Base Construcing
Derived Constructing
Base Destrucing
*************分割线*************
Base Construcing
Derived Constructing
Derived Destructing
Base Destrucing
  • As can be seen, when using the parent class pointer if no virtual destructor polymorphic (Virtual), then, it is only called Base * Base class destructor, and not to find subclass analysis destructor.
  • Nor can change Derived Base * pointer, because Derived pointers one day may become another type of parent

Guess you like

Origin www.cnblogs.com/superzou/p/11892424.html