Search code examples
c++dynamic-cast

Incomlete object of class


Base * pba = new Derived; Base * pbb = new Base;

Even though both are pointers of type Base*, pba actually points to an object of type Derived, while pbb points to an object of type Base. Therefore, when their respective type-casts are performed using dynamic_cast, pba is pointing to a full object of class Derived, whereas pbb is pointing to an object of class Base, which is an incomplete object of class Derived.

What does an incomplete object of class Derived means?


Solution

  • Base does not have member variables and/or member methods declared in Derived, and is therefore incomplete; As this is frequently the case, dynamic_cast forbids the casting of an actual parent type to its derived type.

    Simply put: Derived is a Base, but Base is not a Derived, and dynamic_cast will not cast something into something it is not. That requires reinterpret_cast and is a recipe for undefined behavior.

    Side note:

    If you are going to ask questions about code examples from cplusplus.com you should link them.

    I found your snippet here http://www.cplusplus.com/doc/tutorial/typecasting/ under dynamic cast.