mercredi 27 juillet 2016

Method call after invalid C-style cast works

So I'm trying to learn a bit more about the differences between C-style-casts, static_cast, dynamic_cast and I decided to try this example which should reflect the differences between C-style-casts and static_cast pretty good.

class B
{
public:
    void hi() { cout << "hello" << endl; }
};

class D: public B {};

class A {};

int main()
{
    A* a = new A();
    B* b = (B*)a;
    b->hi();
}

Well this code snippet should reflect that the C-style-cast goes very wrong and the bad cast is not detected at all. Partially it happens that way. The bad cast is not detected, but I was surprised when the program, instead of crashing at b->hi();, it printed on the screen the word "hello".

Now, why is this happening ? What object was used to call such a method, when there's no B object instantiated ? I'm using g++ to compile.

Aucun commentaire:

Enregistrer un commentaire