c++rtti

Run-time type information in C++


What is runtime type control in C++?


Solution

  • It enables you to identify the dynamic type of a object at run time. For example:

    class A
    {
       virtual ~A();
    };
    
    class B : public A
    {
    }
    
    void f(A* p)
    {
      //b will be non-NULL only if dynamic_cast succeeds
      B* b = dynamic_cast<B*>(p);
      if(b) //Type of the object is B
      {
      }
      else //type is A
      { 
      }
    }
    
    int main()
    {
      A a;
      B b;
    
      f(&a);
      f(&b);
    }