#include <iostream>
#include <typeinfo> // Header for typeid operator
using namespace std;
// Base class
class MyBase {
public:
virtual void Print() {
cout << "Base class" << endl;
};
};
// Derived class
class MyDerived : public MyBase {
public:
void Print() {
cout << "Derived class" << endl;
};
};
int main()
{
// Using typeid on built-in types types for RTTI
cout << typeid(100).name() << endl;
cout << typeid(100.1).name() << endl;
// Using typeid on custom types for RTTI
MyBase* b1 = new MyBase();
MyBase* d1 = new MyDerived();
MyBase* ptr1;
ptr1 = d1;
cout << typeid(*b1).name() << endl;
cout << typeid(*d1).name() << endl;
cout << typeid(*ptr1).name() << endl;
if ( typeid(*ptr1) == typeid(MyDerived) ) {
cout << "Ptr has MyDerived object" << endl;
}
// Using dynamic_cast for RTTI
MyDerived* ptr2 = dynamic_cast<MyDerived*> ( d1 );
if ( ptr2 ) {
cout << "Ptr has MyDerived object" << endl;
}
}
OUTPUT:
i
d
6MyBase
9MyDerived
9MyDerived
Ptr has MyDerived object
Ptr has MyDerived object
Monday, December 6, 2010
RTTI examples
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment