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:

  1. static type is the type it was declared to point to (Compiler knows this)
  2. 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:

Book* b;
string choice;
cin >> choice;
if (choice == "Book")  {
	b = new Book{...};
} else {
	b = new Text{...};
}
cout << b->isHeavy() << endl;

b has two types associated with it:

  1. static type: b is a Book*, compiler knows this
  2. dynamic type: b is either pointing to a Book or Text 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.