Thursday 21 January 2016

Type Casting in C++


dynamic_cast: Only upcast allowed

  Base * pb1 = new Derived;
  Base * pb2 = new Base;
  Derived * pd;

  pd = dynamic_cast<Derived*>(pb1); //Success. pd will be Non-Null value
  pd = dynamic_cast<Derived*>(pb2); //Failure. pd will be NULL


static_cast: Upcast and downcast both allowed

  Base * pb = new Base;
  Derived * pd = static_cast<Derived*>(pb); //Success. Programmer should ensure the safety.


reinterpret_cast: converts any pointer type to any other pointer type, even of unrelated classes.

  class A { /* ... */ };
  class B { /* ... */ };
  A * a = new A;
  B * b = reinterpret_cast<B*>(a); 

const_cast: manipulates the constness of the object pointed by a pointer, either to be set or to be removed.

  void display (char * str)
  {
    cout << str << '\n';
  }

  int main () {
    const char * c = "sample text";
    display ( const_cast<char *> (c) );
    return 0;
  }

No comments:

Post a Comment