Search code examples
c++reinterpret-cast

reinterpret_cast and cross casting


#include<iostream>

struct I1
{ 
    virtual void nb1()=0;
    virtual ~I1(){}
};

struct I2
{ 
    virtual void nb2()=0;
    virtual void nb22()=0;
    virtual ~I2(){}
};

struct C12 : I1, I2
{
    virtual void nb1(){std::cout << "nb\n";}    
    virtual void nb2(){std::cout << "nb2\n";}    
    virtual void nb22(){std::cout << "nb22\n";}
};

int main()
{
    I2 * p2 = new C12; 
    I1 * p1 = reinterpret_cast<I1*>(p2);
    return 1;
}

Is there any contraindications to use a reinterpret_cast here ? Should I mandatory use dynamic_cast?

Is it ok ONLY if I1 and I2 are pure virtual ?


Solution

  • The reinterpret_cast is unsafe; you should always use dynamic_cast. It is irrelevant that I1 and I2 are pure virtual classes; as subobjects of C12 they have nonzero storage requirements. Indeed, in the following program:

    int main() {
        I2 * p2 = new C12; 
        I1 * p1 = reinterpret_cast<I1*>(p2);
        std::cout << p2 << '\n';
        std::cout << p1 << '\n';
        std::cout << dynamic_cast<I1*>(p2) << '\n';
        p1->nb1();
    }
    

    the output is:

    0x14de0c8
    0x14de0c8
    0x14de0c0   // !!!
    nb2         // !!!
    

    You may be thinking of the empty base optimization (1.8p5); but this does not apply to classes with virtual methods, which require a vptr.