/********************************************************************************** *** FILE: cast.cpp *** DATE: 03/07/2004 *** AUTHOR: Daniel Dementiev *** GOAL: This small program illustrates the dynamic_cast<...> operator. *** To see what the static_cast<...> operator does, uncomment the lines *** at the end of the main() function. *** Use: *** C:\> cl cast.cpp /EHsc /GR *** to compile using the MS Visual C++ command line compiler. **********************************************************************************/ #include using namespace std; class A { private: int a; public: A() : a(rand()%10) {}; A(int v) : a(v) {}; virtual int get() { return a; }; }; class B : public A { private: int b; public: B() : b(rand()%10) {}; B(int v) : b(v) {}; virtual int get() { return b; }; }; class C { private: int c; public: C() : c(rand()%10) {}; C(int v) : c(v) {}; virtual int get() { return c; }; }; void main() { A *pb = new B(5); C *pc = new C(10); B *p; p = dynamic_cast(pb); if( p ) cout<<"Variable pb contains a poinnter to an object of the type B\n"; else cout<<"Variable pb does NOT contain a poinnter to an object of the type B\n"; p = dynamic_cast(pc); if( p ) cout<<"Variable pc contains a poinnter to an object of the type B\n"; else cout<<"Variable pc does NOT contain a poinnter to an object of the type B\n"; /* // uncomment these lines to see what the static_cast<> does cout<<"\n--------------------\nStatic casting:\n"; p = static_cast(pb); cout<<"After static conversion: value stoder in 'pb' location is "<get()<(pc); cout<<"After static conversion: value stoder in 'pc' location is "<get()<