/* Author. Arun Somasundaram, CSE Dept, OSU. Simple program illustrating Casting (Implicit, dynamic_cast, static_cast, reinterpret_cast, const_cast) and typeid usage */ #include #include using namespace std; class First { private: int f1; int f2; public: First(){} First(int val){ f1 = val; f2 = 10*f1; cout << "First f1 val is " << f1 << endl; cout << "First Constructor called " << endl; } int getF1Val(){return f1;} int getF3Val(){return 3;} int getF2Val(){return f2;} }; class Second { private: int s1; int s2; public: Second(){} Second(int val){ s1 = val; s2 = 20*val; } Second (First f){ s1 = f.getF1Val(); s2 = s1*20; cout << "Second s1 val is " << s1 << endl; cout << "Second Constructor called " << endl; } int getS1Val(){return s1;} int getS2Val(){return s2;} }; class FirstDerived : public First{ }; class Third { public: virtual void func(){} }; class ThirdDerived: public Third{ }; void implicitClassCast(){ //Implicit casting between classes which has constructor conversion First f(5); Second s = f; } void printChars(char *s){ cout << s << endl; } void explicitClassCast(){ First f1(11); FirstDerived fD1; First * pF2; FirstDerived * pFD2; Second *pS; //pS = (Second *) (&f1); //Unpredictable runtime behavior //cout << "s2 " << pS->getS2Val() << endl; //Dynamic casting - used with pointers and references //Ensures casting validity //pS = dynamic_cast (&f1); //Error. pF2 = dynamic_cast (&fD1); //pFD2 = dynamic_cast (&f1); //Error. Why? //Dynamic casting with a polymorphic base. Third *pT1 = new ThirdDerived(); Third *pT2 = new Third(); ThirdDerived *pTD1; ThirdDerived *pTD2; pTD1 = dynamic_cast(pT1); pTD2 = dynamic_cast(pT2); if (pTD1 == NULL) cout << "pTD1 NULL" << endl; if (pTD2 == NULL) cout << "pTD2 NULL" << endl; //Static casting performs conversions between related classes pFD2 = static_cast (&f1); //reinterpret casting performs conversions between any pointers pS = reinterpret_cast (&f1); //Const casting can be used to set or remove the constant //nature of the object const char *constStr = "HelloConst"; //printChar(constStr); //Error? Why? printChars(const_cast (constStr)); delete [] constStr; //typeid can provide the type of an expression cout << typeid(f1).name() << endl; cout << typeid(pFD2).name() << endl; cout << typeid(*pTD1).name() << endl; } int main(){ implicitClassCast(); explicitClassCast(); return 0; }