关于类的虚拟析构函数、纯虚拟析构函数

来源:互联网 发布:vb.net 读取资源文件 编辑:程序博客网 时间:2024/05/21 10:34
#include<iostream>using namespace std;// 1st pair base & derivedstruct Node{    Node()  {cout<<"This is constructor of Node."<<endl;};    ~Node() {cout<<"This is destructor of Node."<<endl;};};struct MathNode: public Node{    MathNode()  {cout<<"This is constructor of MathNode."<<endl;};    ~MathNode() {cout<<"This is destructor of MathNode."<<endl;};};// 2nd pair base & derivedstruct Node_2{    Node_2()  {cout<<"This is constructor of Node_2."<<endl;};    virtual ~Node_2() {cout<<"This is destructor of Node_2."<<endl;}; // virtual function};struct MathNode_2: public Node_2{    MathNode_2()  {cout<<"This is constructor of MathNode_2."<<endl;};    ~MathNode_2() {cout<<"This is destructor of MathNode_2."<<endl;};};// 3rd pair base & derivedstruct Node_3{    Node_3()  {cout<<"This is constructor of Node_3."<<endl;};    virtual ~Node_3() {cout<<"This is destructor of Node_3."<<endl;};     virtual void foo() = 0; // pure virtual function to make the class abstract};struct MathNode_3: public Node_3{    MathNode_3()  {cout<<"This is constructor of MathNode_3."<<endl;};    ~MathNode_3() {cout<<"This is destructor of MathNode_3."<<endl;};};int main(){    cout<<"Example 1"<<endl;    MathNode* a = new MathNode; // type: MathNode*    delete a; // derived class destructor is called, and then the base class's    cout<<"Example 2"<<endl;    Node* b = new MathNode; // type: Node*    delete b; // only base class destructor is called    cout<<"Example 3"<<endl;    Node_2* c = new MathNode_2; // type: Node_2*    delete c; // derived class destructor is called, and then the base class's    //cout<<"Example 4"<<endl;    //MathNode_3* d = new MathNode_3; // type: Node_3* (Error due to abstract class can't be instantiated)    cout<<"END."<<endl;    return 0;}


Output:

Example 1This is constructor of Node.This is constructor of MathNode.This is destructor of MathNode.This is destructor of Node.Example 2This is constructor of Node.This is constructor of MathNode.This is destructor of Node.Example 3This is constructor of Node_2.This is constructor of MathNode_2.This is destructor of MathNode_2.This is destructor of Node_2.END.


Summary:

1. "new" calls base class constructor, then derived class constructor; "delete" calls destructor in reverse order;

2. If use base class pointer to point to derived class instance, then the called non-virtual functions are from base class, while virtual functions (whose addresses are recorded in virtual function table vtable that is created by compiler on the construction of object. Each object has its own vtable) are from the object of derived class.

3. Pure virtual member function makes the class abstract. We can use it to prevent instantiating the base class (compiler error), while we can override the same function in derived class to make it concrete class.


Related articles:

1. C++虚函数浅析

2. pure Virtual Functions

3. C++函数调用内存分配机制

0 0