Riken
Riken

Reputation: 75

How is the underlying type of an object determined at runtime?

Given the following block of code:

class BaseClass
{
public:
    virtual void hello() { cout << "Hello from Base" << endl; }
};

class DerivedClass : public BaseClass
{
public:
    void hello() { cout << "Hello from Derived" << endl; }
};

int main()
{
    BaseClass base;
    DerivedClass derv;

    BaseClass* bp = &base;
    bp->hello();
    bp = &derv;
    bp->hello();
}

How is the type that bp is pointing at determined at runtime? I understand it is dynamically bound, but what is the mechanism that does so? I'm confused because typically the answer is the compiler, however because it is dynamic, it is not the case in this example (or am I mistaken? I assume the compiler this up ahead of time, but what indicates that bp now points to a DerivedClass?). I'm also coming from C#, so this idea is foreign to me seeing as this is native code without the CLR.

Upvotes: 0

Views: 86

Answers (1)

Collin
Collin

Reputation: 12287

When the DerivedClass is constructed, an invisible member is inserted into it's data. That member points to something called a vtable. The vtable has function pointers to the virtual function implementations of the derived class.

Each concrete class (a class which you can instantiate) has it's own vtable somewhere in memory. These tables only get generated if you have virtual functions, part of C++'s motto about not paying for things you don't use.

When the compiler sees bp->hello(), it knows to look for that vtable pointer, and calls the correct function.

Upvotes: 6

Related Questions