Static vs. Dynamic Type Pointer
A pointer to a parent class P
can point to an instance of P
(if P is not abstract) or any inheritance descendant class, with 2 types associated to it:
- static type is the type it was declared to point to (Compiler knows this)
- dynamic type is the type of the object it is currently pointing to (or nullptr). May depend on user-input, cannot be determined by the compiler
In the example below:
b
has two types associated with it:
- static type:
b
is aBook*
, compiler knows this - dynamic type:
b
is either pointing to aBook
orText
object depending on user-input, cannot be determined by the compiler
Danger
The pointer can only point to children or same type of the base class.
Thus, the dynamic type of a (non-nullptr) pointer is always an inheritance descendent of (or the same as) its static type.