Search code examples
inheritancepointersconstructorvirtualvtable

why both constructor of Base class and Drive class run when initialize instance of Drive class


#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;
}

The output of this program is

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

in my opinion, just constructor of Drive class run when i initialize a Drive instance, but in this program, code in Base's constructor also run. And follow the output, there is thing so weird, we just have 1 instance, 1 virtual Pointer but we have 2 Vtable.


Solution

  • Because when you run the constructor of an inherited class, the constructor of it's super class is run automatically. It's like your compiler put's for you an appeal for the Base constructor in the first line of your Drive constructor. For your compiler, the Drive constructor looks something like this:

        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;
        }