2 years ago

#19795

test-img

bradgonesurfing

Is it allowed to reinterpret cast from ptr of parent type to ptr of child type if the child class adds no data members or virtual methods?

Is this allowed?

#include <iostream>

class Foo {
public:
    int a;
    int b;
};

class Bar : public Foo
{
   // NO data members added
   public:
   inline int sum() const { return a+b;};
};

int main(){
    Foo * foo = new Foo{10,20};
    Bar * bar = reinterpret_cast<Bar *>(foo);
    std::cout << bar->sum() << std::endl;
}

Note that the above code works in GCC, CLANG and MSVC. The question is, is this undefined behaviour or is this allowed? My actual use case is a subclass of boost::shared_ptr which only adds some helper methods but the above code is a simple demonstration of concept.

See https://godbolt.org/z/zzoxj7Maz for a live version

c++

c++14

undefined-behavior

reinterpret-cast

0 Answers

Your Answer

Accepted video resources