【C++ 继承】构造函数 与 析构函数

普通继承中的构造函数与析构函数

【注意】定义一个对象时先调用基类的构造函数、然后调用派生类的构造函数;析构的时候恰好相反:先调用派生类的析构函数、然后调用基类的析构函数。

#include <iostream>
using namespace std;

class Base {
public:
    Base() { cout << "Base contruction" << endl; }
    virtual ~Base() { cout << "Base deconstruction" << endl; }
};

class Derived : public Base {
public:
    Derived(int i) {
        num = i;
        cout << "Derived contruction: " << num << endl;
    }
    virtual ~Derived() { cout << "Derived deconstruction: " << num << endl; }
private:
    int num;
};

int main()
{
    Derived derived(1);

    Base* basePtr;
    basePtr = new Derived(2);
    delete basePtr;
}

输出结果:

 

虚继承中的构造函数与析构函数

含有虚基类 的对象的构造顺序与一般的顺序稍有区别:首先使用 提供给最底层派生类的构造函数的初始值初始化该对象的虚基类子部分,接下来按照直接基类在派生类列表出现的次序对其进行初始化。

注意:

  • 一个类可以有很多虚基类,此时,这些虚的子对象按照它们在派生列表出现的顺序从左自右一次构造。
  •  对于析构函数,和往常一样,对象的销毁顺序与构造顺序正好相反。

1. 示例

#include <iostream>

class Character {
public:
    Character() { std::cout << "Character Constructor" << std::endl; }
    ~Character() { std::cout << "Character Destructor" << std::endl; }
};

class BookCharacter : public Character {
public:
    BookCharacter() { std::cout << "BookCharacter Constructor" << std::endl; }
    ~BookCharacter() { std::cout << "BookCharacter Destructor" << std::endl; }
};

class ZooAnimal {
public:
    ZooAnimal() { std::cout << "ZooAnimal Constructor" << std::endl; }
    ~ZooAnimal() { std::cout << "ZooAnimal Destructor" << std::endl; }
};

class Bear : public virtual ZooAnimal {
public:
    Bear() { std::cout << "Bear Constructor" << std::endl; }
    ~Bear() { std::cout << "Bear Destructor" << std::endl; }
};

class ToyAnimal {
public:
    ToyAnimal() { std::cout << "ToyAnimal Constructor" << std::endl; }
    ~ToyAnimal() { std::cout << "ToyAnimal Destructor" << std::endl; }
};

class TeddyBear : public BookCharacter, public Bear, public virtual ToyAnimal {
public:
    TeddyBear() { std::cout << "TeddyBear Constructor" << std::endl; }
    ~TeddyBear() { std::cout << "TeddyBear Destructor" << std::endl; }
};

int main()
{
    TeddyBear tb;
    return 0;
}

输出:

 

参考资料

1. 基类和派生类析构函数执行顺序

posted @ 2018-06-22 20:53  苏格拉底的落泪  阅读(214)  评论(0编辑  收藏  举报