How dynamic cast is working between two classes which has common derived class

Viewed 74

In below code I have Derived1 class which is derived from two classes/struct (I1 and Base). Using this relation I am able to dynamic cast Base type pointer to I1 type. Which I could not understand in terms in Vtable. Can someone explain, how did this work (in terms of Vtable).

 struct Base
 {    
    virtual ~Base() {};
 };

 struct I1
 { 
     virtual void f1() = 0;
 };

//---------------------------------------------
struct Derived1 : public Base, public I1 
{
    void f1() { std::cout << __FUNCTION__ << std::endl; }
};

//---------------------
Base* getBase()
{
    return new Derived1;
}

int main()
{

    Base* base = getBase();

I did not understand how this below dynamic cast worked when there is no parent chid relation between below two classes. How did this work?

    I1* i1 = dynamic_cast<I1*>(base);    
    i1->f1();

    return 0;
}
0 Answers
Related