Comparing Run-Time Type With typeid Operator

27 Sep 2013

How to deterime run-time type (dynamic type) of an object that is referred to by a pointer or a reference?

Use typeid operator in C++. This operator provides a program the ability to retrieve the actual derived type of the object referred to by a pointer or a reference. Let’s see some example:

// comparing type_info objects
#include <iostream>   // std::cout
#include <typeinfo>   // operator typeid

struct Base {};
struct Derived : Base {};
struct Poly_Base {virtual void Member(){}};
struct Poly_Derived: Poly_Base {};

typedef int my_int_type;

int main() {
  std::cout << std::boolalpha;

  // fundamental types:
  std::cout << "int vs my_int_type: ";
  std::cout << ( typeid(int) == typeid(my_int_type) ) << '\n';

  // class types:
  std::cout << "Base vs Derived: ";
  std::cout << ( typeid(Base)==typeid(Derived) ) << '\n';

  // non-polymorphic object:
  Base* pbase = new Derived;

  std::cout << "Base vs *pbase: ";
  std::cout << ( typeid(Base)==typeid(*pbase) ) << '\n';

  // polymorphic object:
  Poly_Base* ppolybase = new Poly_Derived;

  std::cout << "Poly_Base vs *ppolybase: ";
  std::cout << ( typeid(Poly_Base)==typeid(*ppolybase) ) << '\n';

  return 0;
}

Possible output:

int vs my_int_type: true
Base vs Derived: false
Base vs *pbase: true
Poly_Base vs *ppolybase: false