Sine there seems to be some disagreement between a comment (saying objects have static types) and an answer (saying variables have static types, but objects don't necessarily), I guess I'll throw in my two cents worth on the subject.
In C++, both variables and objects have static types. When you create an object (e.g., whether global, local, or created with new
) you have to give a static specification of its type.
Likewise, when you create a variable, it always has a static type. For example, T *x
and Tprime &y
define x
as a pointer to T
, and y
as a reference to TPrime
respectively.
The one place things get dynamic is that it's possible for a pointer or reference to refer not only to the static type for which it is defined, but also to any other type derived from that type. A variable of type "pointer to T
" is really implicitly of type "pointer to T
or any derivative of T
" (and likewise with references).
Therefore, given a variable of type (pointer|reference) to T referring to some object, the pointer itself, and the object to which it refers both have static types -- but they aren't necessarily the same static type.
dynamic_cast
allows you to determine the static type of the referred-to object, even when/if it is/might be different from the static type of the pointer/reference being used to refer to the object. dynamic_cast
also allows you to determine an intermediate type that's not really the static type of the pointer or of the object to which it refers, if the inheritance hierarchy includes some intermediate type between the two. For example, given:
struct base {
virtual ~base() {}
};
struct intermediate : base {};
struct derived : intermediate {};
...we could have something like:
base *b = new derived;
intermediate *i = dynamic_cast<intermediate *>(b);
...and the cast would succeed.