Search code examples
c++inheritancemultiple-inheritancereinterpret-cast

Use of reinterpret_cast


Is there anything wrong with the following code? In particular I'm interested in the use of reinterpret_cast.

class Base1
{
public:
    virtual void foo(){}
};

class Base2
{
public:
    virtual void bar(){}
};

class Derived : public Base1, public Base2
{
};

int main()
{
    Base1* instance1 = new Derived();
    instance1->foo();

    Base2* instance2 = reinterpret_cast<Base2*>(instance1);
    instance2->bar();

    return 0;
}

Solution

  • reinterpret_cast doesn't know how to handle casting between siblings (for example in vtable implementations it won't fix up the this pointer) so it will definitely not work. Note that it may appear to do what you expect. You'll want to use dynamic_cast in this case, or alternately static_cast to derived and use the implicit conversion to base2.