Question

TYPE& dynamic_cast<TYPE&> (object);
TYPE* dynamic_cast<TYPE*> (object);

For example we can get type like this. C++ is static typed language, why can we get type at runtime

Was it helpful?

Solution

Variables in C++ have a statically determined type. Objects don't necessarily. You only need to handle objects through variables of statically known type.

Examples:

int * p = new int[argc];   // there is an object whose dynamic type is int[argc]

Base * p = new Derived;    // *p has dynamic type Derived

Base * q = rand() % 2 ? new Derived1 : new Derived2;    // ???

OTHER TIPS

C++ is a static type language. It means you can not create a new class/type declaration in run-time and instance an object/variable of it, which is possible in Javascript or PHP.

dynamic_cast is part of RTTI, the C++ attempt to give information of types in run-time. When you cast an object via dynamic_cast, you aren't creating new type, you're just doing a polymophic thing.

However, you can say C++ is both static and dynamic type.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top