Type Casting

Introduction

Converting an expression of a given type into another type is known as type-casting.

Implicit conversion

Implicit conversions do not require any operator.

Example 1: The value of a has been promoted from short to int without specifying any type-casting operator.

short a = 2000;
int b;
b = a;

Example 2: Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. In the following example, an implicit conversion happened between objects of class A and class B, because B has a constructor that takes an object of class A as parameter.

class A();
class B { public: B(A a) {} };
 
A a;
B b = a;

Explicit Conversion

Two ways for explicit type conversion:

  • Functional
  • c-like

Example:

short a = 2000;
int b;
b = (int) a; //c-like cast notation
b = int (a); // functional notation

Conversions Between Classes

Four specific casting operators:

  • dynamic_cast <new_type> (expression)
  • reinterpret_cast <new_type> (expression)
  • static_cast <new_type> (expression)
  • const_cast <new_type> (expression)

dynamic_cast

dynamic_cast can be used to ensure that the result of the type conversion is a valid complete object of the requested class. So, dynamic_cast is always successful when we cast a class to one of its base classes.

Example:

class CBase { };
class CDerived: public CBase { };
 
CBase b; CBase* pb;
CDerived d; CDerived* pd;
 
pb = dynamic_cast<CBase*>(&d);     // ok: derived-to-base
pd = dynamic_cast<CDerived*>(&b);  // wrong: base-to-derived

static_cast

Example:

class CBase {};
class CDerived: public CBase {};
CBase * a = new CBase;
CDerived * b = static_cast<CDerived*>(a);

reinterpret_cast

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

const_cast

// const_cast
#include <iostream>
using namespace std;
 
void print (char * str)
{
  cout << str << endl;
}
 
int main () {
  const char * c = "sample text";
  print ( const_cast<char *> (c) );
  return 0;
}
Bibliography
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.