Wednesday, March 8, 2017

When to use dynamic_cast and static_cast in C++

Dynamic Cast:
  • Dynamic cast is used to convert a pointer (or reference) to base type to pointer (or reference) to derived type, iff the base pointer/reference refers to derived type. This is called down casting. (Base -> Derived)
  • This type of casting is used when these two types are polymorphic (means base class should have virtual methods).
  • No need of explicit type casting when we want to convert a pointer (or reference) to derived type to pointer (or reference) to base type. This is called up casting. (Derived-> Base )
  • If you use dynamic_cast for non-polymorphic classed it will through compile time error
  • This cast is mainly used to execute the derived type specific functionality when we have base class pointer/reference. (Throgh base pointer/reference we cannot access derived type specific fucntionality)
  • dynamic_cast safely convers to derived type in run-time, if it fails to convert it will return NULL when target is pointer type, throws bad_cast exception when target type to convert is reference.
Example:
 #include<iostream>  
 #include<typeinfo>  
 using namespace std;  
   
 class Base  
 {  
 public:  
   virtual void display() {  
     cout<<"Base: Display "<<endl;  
   }  
 };  
   
 class Derived: public Base  
 {  
 public:  
   void display() {  
     cout<<"Derived: Display "<<endl;  
   }  
   void myderfun() {  
     cout<<"Derived: myderfun "<<endl;  
   
   }  
 };  
   
 int main()  
 {  
   Base baseobj;  
   Derived derivedobj;  
   
   Base *pbaseobj = new Base();  
   pbaseobj->display();  
   
   Base *pbaseRefDerived = new Derived();  
   pbaseRefDerived->display();  
   
   Derived *pderivedobj1 = dynamic_cast<Derived*>(pbaseRefDerived); // valid  
   pderivedobj1->display();  
   
   Derived *pderivedobj2 = dynamic_cast<Derived*>(&baseobj); // invalid, returns null pointer  
   if(pderivedobj2)  
     pderivedobj2->display();  
   
   Derived &rderivedobj1= dynamic_cast<Derived&>(*pbaseRefDerived); // valid  
   rderivedobj1.display();  
   
   try {  
   Derived &rderivedobj2= dynamic_cast<Derived&>(baseobj); // invalid, throws bad_cast exception  
   rderivedobj2.display();  
   }  
   catch(bad_cast e) {  
     cout<<"exception caught:: "<<e.what()<<endl;  
   }  
   return 0;
 }  
   
   



Output: 


Static Cast:
  • Static cast is used to convert pointers of related class types (should have inheritance relation for class types)
  • It can not convert between unrelated class types
  • It is used to force the implicit conversion ex: short to int, int to float conversion
  • It can also used to convert void* to specific pointer type iff void* was obtained from that specific pointer type. 
  • There is no overhead of runtime type checking in static_cast as in dynamic_cast

Example: 

 #include<iostream>  
 using namespace std;  
 class Base  
 {  
 public:  
   void display() {  
     cout<<"Base: Display b:"<<b<<endl;  
   }  
   int b;  
 };  
   
 class Derived: public Base  
 {  
 public:  
   void display() {  
     cout<<"Derived: Display b:"<<b<<" d:"<<d<<endl;  
   }  
   void myderfun() {  
     cout<<"Derived: myderfun "<<endl;  
   }  
   int d;  
 };  
   
  int main()   
  {   
   Base *pbaseobj = new Base();  
   pbaseobj->b = 1;  
   pbaseobj->display();  
   
   Derived *pDerived = new Derived();  
   pDerived->b = 2;  
   pDerived->d = 3;  
   
   Base *pbaseRefDerived = pDerived;  
   pbaseRefDerived->display();  // display() not a virtual function 
   
   Derived *pderivedobj1 = static_cast<Derived*>(pbaseobj);  
   pderivedobj1->display();  
   
   Derived *pderivedobj2 = static_cast<Derived*>(pbaseRefDerived);  
   pderivedobj2->display();  
   
  return 0;  
   
  }  
   
Output:




3 comments:

  1. If you're looking to lose kilograms then you have to start using this totally brand new personalized keto meal plan.

    To create this service, licenced nutritionists, personal trainers, and professional cooks have joined together to develop keto meal plans that are efficient, suitable, price-efficient, and enjoyable.

    From their grand opening in 2019, 1000's of people have already transformed their figure and health with the benefits a proper keto meal plan can provide.

    Speaking of benefits: in this link, you'll discover eight scientifically-tested ones offered by the keto meal plan.

    ReplyDelete
  2. Borgata Hotel Casino & Spa in Atlantic City - Mapyro
    View directions, reviews and information for 경상북도 출장샵 Borgata 화성 출장안마 Hotel Casino & Spa in Atlantic City, NJ. Address: 3131 S. Atlantic 통영 출장안마 City Drive, 경상남도 출장마사지 Atlantic City, NJ 08401. 양산 출장안마

    ReplyDelete