Object-Oriented Programming

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:

  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.

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, but mike->cleanRoom() is not, because cleanRoom() was not declared as a virtual function in the base class.