typeid for polymorphic class : typeid « Development « C++






typeid for polymorphic class

  
#include <iostream>
#include <typeinfo>
#include <exception>
using namespace std;

class CBase {virtual void f(){} };
class CDerived : public CBase {};

int main () {
  try {
    CBase* a = new CBase;
    CBase* b = new CDerived;
    cout << "a is: " << typeid(a).name() << '\n';
    cout << "b is: " << typeid(b).name() << '\n';
    cout << "*a is: " << typeid(*a).name() << '\n';
    cout << "*b is: " << typeid(*b).name() << '\n';
  } catch (exception& e) { cout << "Exception: " << e.what() << endl; }
  return 0;
}
  
    
  








Related examples in the same category

1.Here is a simple example that uses typeidHere is a simple example that uses typeid
2.An example that uses typeid on a polymorphic class hierarchyAn example that uses typeid on a polymorphic class hierarchy
3.An example that uses typeid for base and derived classesAn example that uses typeid for base and derived classes
4.Demonstrate runtime type id.
5.A simple example that uses typeid.
6.Use a reference with typeid.
7.Demonstrating run-time type id.
8.typeid Can Be Applied to Template Classestypeid Can Be Applied to Template Classes
9.Demonstrate == and != relative to typeid.Demonstrate == and != relative to typeid.