Search code examples
c++virtualreinterpret-cast

reinterpret_cast and virtual between unrelated types


Would someone kindly explain why the following bit of code works, I've tested it on Visual Studio .NET 2008, g++ on Cygwin and ideone.com. More important I'd like to know if its valid. Note that A and B are unrelated types.

Edit: following @leftaroundabout's comment I made the following change to my code

#include <iostream>
#include <cstdlib>

class A
{
public:
    virtual void Bar()
    {
        std::cout << "A::Bar() -> " << this << std::endl;
    }

    virtual void Foo()
    {
        std::cout << "A::Foo() -> " << this << std::endl;
    }   
};

class B
{
public:
    virtual void Foo()
    {
        std::cout << "B::Foo() -> " << this << std::endl;
    }
};

int main()
{
    B* b = reinterpret_cast<B*>( new A );
    b->Foo();   
    return EXIT_SUCCESS;
}

The program outputs the message:

A::Bar() -> 0x9806008

Basically the first virtual method is called regardless of what it is called.


Solution

  • It only woks by luck, nothing in the standard says it should work - the cast is invalid. The compiler is likely to lay out both classes exactly the same way in memory, but there is no such obligation AFAIK.

    Try adding:

    virtual void Bar()
    {
        std::cout << "A::Bar() -> " << this << std::endl;
    }
    

    before Foo in A and see what happens - chances are Bar will be called when b->Foo() is run.