C ++ is a static typed language, why can we get a type at runtime

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

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

+1
source share
3 answers

Variables in C ++ have a statically defined type. Objects are optional. You only need to process objects through variables of a 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;    // ???
+5
source

C ++ is a static type language. This means that you cannot create a new class / type declaration at run time and an instance of an object / variable, which is possible in Javascript or PHP.

dynamic_cast RTTI, ++ . dynamic_cast, , .

, ++ , .

+2

, -, (, ) (, , ), , .

++ . (, , new), .

, , . , T *x Tprime &y x T y TPrime .

, , , , , , . " T" " T T" ( ).

, ( | ) T, , , , , .

dynamic_cast , / / /, . dynamic_cast , , , . , :

struct base {
    virtual ~base() {}
};

struct intermediate : base {};

struct derived : intermediate {};

... - :

base *b = new derived;
intermediate *i = dynamic_cast<intermediate *>(b);

... .

+2

All Articles