Static vs. Dynamic Type of 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.
Example
Old example from CS138
In the above example, the static type of the pointer mike
is Parent, but its dynamic type is Child.
Important
It is the static type of the Pointer that determines what methods can be called through it.
So
mike->speak()
is legal, butmike->cleanRoom()
is not, becausecleanRoom()
was not declared as a virtual function in the base class.