#include #include using namespace std; class Element { public: virtual ~Element() { } }; class This : public Element { public: string thiss() { return "This"; } }; class That : public Element { public: string that() { return "That"; } }; class TheOther : public Element { public: string theOther() { return "TheOther"; } }; void main( void ) { Element* list[] = { new That(), new This(), new TheOther() }; for (int i=0; i < 3; i++) { // 1. print out the name of the type of each element // 2. use typeid() to try to find the This* element // 3. use static_cast() to try to find the This* element // 4. use dynamic_cast() to try to find the This* element // 5. use dynamic_cast() to call each class' peculiar method } } #if 0 void main( void ) { Element* list[] = { new That(), new This(), new TheOther() }; for (int i=0; i < 3; i++) cout << typeid(list[i]).name() << '\n'; } // class Element * // class Element * // class Element * void main( void ) { Element* list[] = { new That(), new This(), new TheOther() }; for (int i=0; i < 3; i++) if (typeid(list[i]) == typeid(This*)) cout << "element is This*\n"; else if (typeid(list[i]) == typeid(Element*)) cout << "element is Element*\n"; } // element is Element* // element is Element* // element is Element* void main( void ) { Element* list[] = { new That(), new This(), new TheOther() }; for (int i=0; i < 3; i++) if (static_cast(list[i])) cout << "element is This*\n"; else if (static_cast(list[i])) cout << "element is Element*\n"; } // element is This* // element is This* // element is This* void main( void ) { Element* list[] = { new That(), new This(), new TheOther() }; for (int i=0; i < 3; i++) if (dynamic_cast(list[i])) cout << "element is This*\n"; else if (dynamic_cast(list[i])) cout << "element is Element*\n"; } // element is Element* // element is This* // element is Element* void main( void ) { Element* list[] = { new That(), new This(), new TheOther() }; This* one; That* two; TheOther* thr; for (int i=0; i < 3; i++) if (one = dynamic_cast(list[i])) cout << one->thiss() << '\n'; else if (two = dynamic_cast(list[i])) cout << two->that() << '\n'; else if (thr = dynamic_cast(list[i])) cout << thr->theOther() << '\n'; } // That // This // TheOther #endif