Pavel Beliy
Pavel Beliy

Reputation: 544

Is this code standard compliant or not?

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

Answers (1)

Columbo
Columbo

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 type X, or of a type derived from X, the behavior is undefined.

A is not of type B or a type derived from B.

Upvotes: 10

Related Questions