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

By : Riken
Source: Stackoverflow.com
Question!

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.

By : Riken


This video can help you solving your question :)
By: admin