An example that uses typeid on a polymorphic class hierarchy : typeid « Development « C++






An example that uses typeid on a polymorphic class hierarchy

An example that uses typeid on a polymorphic class hierarchy
 


#include <iostream>
#include <typeinfo>
using namespace std;
class Mammal {
public:
  virtual bool laysEggs() { 
    return false; 
  }
};
class Cat: public Mammal {
public:
};
class Platypus: public Mammal {
public:
  bool laysEggs() { 
    return true; 
  }
};
int main()
{
  Mammal *p, AnyMammal;
  Cat cat;
  Platypus platypus;
  p = &AnyMammal;
  cout << "p is pointing to an object of type ";
  cout << typeid(*p).name() << endl;
  p = &cat;
  cout << "p is pointing to an object of type ";
  cout << typeid(*p).name() << endl;
  p = &platypus;
  cout << "p is pointing to an object of type ";
  cout << typeid(*p).name() << 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 for base and derived classesAn example that uses typeid for base and derived classes
3.Demonstrate runtime type id.
4.typeid for polymorphic class
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.