mercredi 30 mai 2018

what happens when you dynamic_cast from derived_1 class to derived_2 class

I am trying to figure out what happens when you dynamic_cast from one derived class to another derived class. Why does the below code raise a segmentation fault? Note that I am not trying to use this code for anything. I merely want to understand what is happening. It's also worth noting that the same code works using static_cast. I can't seem to find any documentation that goes into the finer details of what is happening here. Can somebody explain?

struct base 
{ 
    virtual void printing(){cout<<"base printing"<<endl;};
};
struct derived_1 :public base 
{ 
    virtual void printing(){cout<<"derived_1 printing"<<endl;};
};
struct derived_2 :public base 
{ 
    virtual void printing(){cout<<"derived_2 printing"<<endl;};
};

int main()
{
    base * b = new derived_2();
    derived_1 *d_1 = dynamic_cast<derived_1*>(b);

    // calling printing raises segmentation fault
    d_1->printing(); 
}

Aucun commentaire:

Enregistrer un commentaire