0

I've read the topic Downcasting a base type and I'm still in doubts.

class Base 
{
    int i;
};

class Derived : public Base
{
};

int main()
{    
    Base* x = new Base();
    Derived* y = static_cast<Derived*>(x);

    return 0;
}

Do I understand right that even this code is already wrong and can cause undefined behavior?

I ask it because I can't fully understand the standard phrase:

If the rvalue of type “pointer to cv1 B” points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the result of the cast is undefined.

The word "subobject" confuses me. Here pointer x points in reality just to integer i. But This integer can be considered as a Derived object, isn't it? Because any Deived object is also just an integer. And this integer is clearly a subobject of itself. And so here is no UB.

Or (if this reasoning is wrong) does this phrase imply then that we should always have somewhere a creation of a Derived object? So it should be like here, for example:

Derived* z = new Derived();
// ...
// And only if the actual creation of a Derived instance
// took place somewhere the below code is ok
Base* x = z;
Derived* y = static_cast<Derived*>(x);
Community
  • 1
  • 1
JenyaKh
  • 2,040
  • 17
  • 25

0 Answers0