Run-time Type Information - C++ Example

C++ Example

/* A base class pointer can point to objects of any class which is derived * from it. RTTI is useful to identify which type (derived class) of object is * pointed to by a base class pointer. */ #include class abc // base class { public: virtual ~abc { } virtual void hello { std::cout << "in abc"; } }; class xyz : public abc { public: void hello { std::cout << "in xyz"; } }; int main { abc *abc_pointer = new xyz; xyz *xyz_pointer; // to find whether abc_pointer is pointing to xyz type of object xyz_pointer = dynamic_cast(abc_pointer); if (xyz_pointer != NULL) { std::cout << "abc_pointer is pointing to a xyz class object"; // identified } else { std::cout << "abc_pointer is NOT pointing to a xyz class object"; } // needs virtual destructor delete abc_pointer; return 0; }

Read more about this topic:  Run-time Type Information