// A1.7.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include using namespace std; // Define a base class B and two derived classes D1 and D2 so that // B provides a function, showTypes, that displays the type of B // and the type of any class that derives from B. a client uses // the function as shown below. // // B should not have to know the names of the derived classes: // // D1 d1; d1.showTypes(); // shows type of base and type of d1; // D2 d2; d2.showTypes(); // shows type of base and type of d2; template class B { public: void showTypes() { cout << "\n " << typeid(T).name(); // derived type cout << "\n " << typeid(B).name(); // same format as derived } }; class D1 : public B { }; class D2 : public B { }; class B2 { // must define virtual somewhere to get dynamic typeid public: virtual ~B2() {} // since class has vtble, this points to dynamic type void showMyType() { cout << "\n my type is " << typeid(*this).name(); }; // pass by value to slice to base object void showBaseType(B2 b) { cout << "\n my base type is " << typeid(b).name(); } void showTypes() { showMyType(); showBaseType(*this); } }; class D3 : public B2 {}; class D4 : public B2 {}; int _tmain(int argc, _TCHAR* argv[]) { D1().showTypes(); D2().showTypes(); D3().showTypes(); D4().showTypes(); cout << "\n\n"; return 0; }