[C ++ in-depth analysis] 48. Type recognition in C ++

1 Static type and dynamic type

In object-oriented, there may be a base class pointer to a subclass object, and the base class reference becomes an alias of the subclass object. As shown in the figure, the parent class pointer points to the object of the subclass, we can be divided into static type and dynamic type.
Insert picture description here
Static type: the type of the variable (object) itself
Dynamic type: the actual type of the object pointed to by the pointer (reference)

Look at the following code to perform type conversion. Is this conversion safe? Base is the base class and Derived is the derived class. Is it safe to cast the pointer of the parent class to the pointer of the child class? If the test function is called, the pointer of the Base type is passed in, and the conversion is dangerous. Derived pointers, the conversion process is dangerous.

So whether the base class pointer can be cast to a subclass pointer depends on the dynamic type .
Insert picture description here
How to get dynamic types in C ++? Then look down

2 typeid Get type information

C ++ provides the typeid keyword for obtaining type information

  • The typeid keyword returns the type information of the corresponding parameter
  • typeid returns a type_info class object
  • An exception will be thrown when the parameter of typeid is beating NULL

Take an example to see the use of typeid keyword

#include<iostream>
using namespace std;
#include<typeinfo>
int main()
{
    int i = 0;
    const type_info& tiv = typeid(i);
    const type_info& tii = typeid(int);
    cout << (tiv == tii) << endl;
    return 0;
}

Use of typeid

  • When the parameter is type : return static type information
  • When the parameter is a variable :
    • There is no virtual function table: return static type information
    • Virtual function table exists: return dynamic type information
// 48-1.cpp
#include<iostream>
#include<typeinfo>
using namespace std;
class Base
{
public:
    virtual ~Base()
    {
    }
};

class Derived : public Base
{
public:
    void print()
    {
        cout << "I'm a Derived." << endl;
    }
};

void test(Base* b)
{
    const type_info& tb = typeid(*b);
    cout << tb.name() << endl;
}
int main()
{
    Base b;
    Derived d;
    test(&b);
    test(&d);
    return 0;
}

You can use typeid to get type information. Base's destructor is a virtual function, so there are virtual function tables in both classes. When variables are passed in, dynamic type information is returned, and you can determine whether the parent pointer or subclass pointer is passed in.

$ g++ 48-1.cpp -o 48-1
$ ./48-1
4Base
7Derived

3 Summary

1. The concept of static types and dynamic types in C ++
2. The typeid keyword is specifically used for type identification

Published 298 original articles · praised 181 · 100,000+ views

Guess you like

Origin blog.csdn.net/happyjacob/article/details/104647977