Friday, April 4, 2008

C++: static types vs. dynamic types

When using polymorphic types it is good to know the difference between the terms dynamic type and static type.
An object can have booth kind of types. The static type is an objects "real" type whereas the dynamic type is a "base class" type.

Base* pObj = new Derived(); // *pObj's static type is "Derived" whereas the dynamic type is "Base"

Easy spoken: the static type is the real type of the object (right hand side type) and the dynamic type is the polymorphic type (left hand side type).

Polymorphy can only be done with types of pointers or references. Casting between static and dynamic type is usually done with C++ dynamic_cast<> opererator. This cast performs a runtime check for ensuring the Base class pointer can be casted into the specified Derived class pointer.