mardi 4 décembre 2018

C style up cast to same hierachical level

I have the following snippet:

#include <iostream>

using namespace std;

class IA 
{
    public:
    virtual void printA() = 0;
    virtual ~IA(){};
};

class IB 
{
    public:
    virtual void printB() = 0;
    virtual ~IB(){}
};

class IC : public IA, public IB 
{
    public:
    void printA() {cout << "hello world a" << endl; }
    void printB() {cout << "hello world b" << endl; }
};

void func(IB* p)
{
    p->printB();
}

int main()
{
    IA* p = new IC;
    p->printA();
    cout << "cast to ib" << endl;
    func((IB*)p);
    return 0;
}

after I executed the code, I got the following result:

hello world a  
cast to ib 
hello world a

my question is, what compiler does with (IB*)p that cause func calls to p->printB() but get result hello a instead of hello b??

what is behind the scene of cast?? what compiler generates for casting?? if I change to func(dynamic_cast<IB*>(p)), it got print b is the correct result.

Aucun commentaire:

Enregistrer un commentaire