Reputation: 544
So the code is
class A
{
public:
int i;
A(){
i = 5;
}
};
class B : public A
{
public:
void someFunc();
};
class C
{
A myObj;
public:
void func(){
B* foo = reinterpret_cast<B*>(&myObj);
foo->someFunc();
}
};
Assuming that classes will stay as they are and never change, is this use of reinterpret_cast correct(i think that it's not)? If not, which exact parts of C++ standard(you can use any edition) are violated here?
Upvotes: 1
Views: 142
Reputation: 61009
Your program does induce UB. §9.3.1/2:
If a non-static member function of a class
X
is called for an object that is not of typeX
, or of a type derived fromX
, the behavior is undefined.
A
is not of type B
or a type derived from B
.
Upvotes: 10