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