Inheritance/Polymorphism  «Prev 

Cast Operator - Exercise

Objective:Given four different situations, choose the most appropriate form of cast operator.

Instructions

You should now be aware of four cast operators in C++:
  1. static_cast
  2. dynamic_cast
  3. reinterpret_cast
  4. const_cast

In each of the 4 given situations presented in the short program below, determine which is the most appropriate type cast to use and explain why you chose it:

class Base { virtual void foo(); ..... };
class Derived : Base { ..... }

void fcn(const Derived* ptr)
{
   void* p; 
    
   Derived* ptr_a = ______cast<Derived*>(p);
   ptr_a = _________cast<Derived*>(0xcafe);
   ptr_a = ________cast<Derived*>(ptr)
   Base* bptr = ______cast<Base*>(ptr_a);
} 

Paste your response below and click the Submit button when you are ready to submit this exercise.