为什么在初始化Drive类的实例时,Base类和Drive类的构造函数都会运行

时间:2012-06-04 07:41:04

标签: inheritance pointers constructor virtual vtable

#include <iostream>
using namespace std;

class Base {
    public:
        Base() {
            cout << "In Base" << endl;
            cout << "Virtual Pointer = " << (int*)this << endl;
            cout << "Address of Vtable = "
            << (int*)*(int*)this << endl;
            cout << "Value at Vtable = "
            << (int*)*(int*)*(int*)this << endl;
            cout << endl;
        }

        virtual void f1() { cout << "Base::f1" << endl; }
};

class Drive : public Base {
    public:
        Drive() {
            cout << "In Drive" << endl;
            cout << "Virtual Pointer = "
            << (int*)this << endl;
            cout << "Address of Vtable = "
            << (int*)*(int*)this << endl;
            cout << "Value at Vtable = "
            << (int*)*(int*)*(int*)this << endl;
            cout << endl;
        }

        virtual void f1() { cout << "Drive::f2" << endl; }
};

int main() {
    Drive d;
    return 0;
}

该程序的输出是

In Base
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C08C
Value at Vtable = 004010F0

In Drive
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C07C
Value at Vtable = 00401217

在我看来,只是在初始化Drive实例时运行Drive类的构造函数,但在此程序中,Base的构造函数中的代码也会运行。并按照输出,有事情如此奇怪,我们只有1个实例,1个虚拟指针,但我们有2个Vtable。

1 个答案:

答案 0 :(得分:1)

因为当你运行继承类的构造函数时,它的超类的构造函数会自动运行。就像你的编译器为你在Drive构造函数的第一行中对Base构造函数的吸引力一样。对于您的编译器,Drive构造函数看起来像这样:

    Drive() {
        Base();
        cout << "In Drive" << endl;
        cout << "Virtual Pointer = "
        << (int*)this << endl;
        cout << "Address of Vtable = "
        << (int*)*(int*)this << endl;
        cout << "Value at Vtable = "
        << (int*)*(int*)*(int*)this << endl;
        cout << endl;
    }