Bogotobogo
contact@bogotobogo.com


Type Cast Operators - 2012
Bookmark and Share
cplusplus logo
Full List of C++ Tutorials




SorakDong


Type-Conversion Operators

Here is the list of type-conversions.

  • a = dynamic_cast<T*>(p)
    Try to convert p into a T*. It may return 0

  • a = dynamic_cast<T&>(*p)
    Try to convert *p into a T&. It may throw bad_cast

  • a = static_cast<T>(p)
    Convert p into a T if a T can be conterted into p's type.

  • a = reinterpret_cast<T>(p)
    Convert p into a T represented by the same bit pattern.

  • a =const_cast<T>(p)
    Convert p into a T by adding or subtracting const.

  • a = (T)v
    C-style cast.

  • a = T(v)
    Functional cast.



Your Ad Here


const_cast

const_cast is typically used to cast away the constness of objects. It is the only C++ style that can do this.

The syntax is:

const_cast < type-name > (expression)

The reason for this operator is that we may have a need for a value that is constant most of the time but that can be changed occasionally. In such a case, we can declare the value as const and use const_cast when we need to alter the value.

Here is a simple example:

#include <iostream>
#include <cstring>
using namespace std;
int main () {
  string str("A123456789");
  const char *cstr = str.c_str();
  char *nonconst_cstr  = const_cast<char *> (cstr) ; 
  *nonconst_cstr ='B';
  cout << nonconst_cstr << endl;
  return 0;
}

Because we casted away the constness of the string, we were able to modify the string from "A123456789" to "B1234567889".





reinterpret_cast

reinterpret_cast is intended for low-level casts that yield implementation-dependent and it would not be portable.

This cast is used for reinterpreting a bit pattern. It is not guaranteed to be portable. In fact, it is best to assume that reinterpret_cast is not portable at all. A typical example is an int-to-pointer to get a machine address into a program:

Register* a = reinterpret_cast<Register*>(0xfa);

This example is the typical use of a reinterpret_cast. We are telling the compiler that the part of memory starting with 0xfa is to be considered a Register.

It converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.

We can cast a pointer type to an integer type that's large enough to hold the pointer representation, but we can't cast a pointer to a smaller integer type or to a floating-point type. The format in which this integer value represents a pointer is platform-specific. We can't cast a function pointer to a data pointer or vice versa.

The syntax is:

reinterpret_cast < type-name > (expression)

Here is an example code:

#include <iostream>
using namespace std;

struct data {
	short a; 
	short b;
};

int main () {
	long value = 0xA2345678;
	data* pdata = reinterpret_cast<data*> (&value);
	cout << pdata->a << endl;
	return 0;
}

Output on my machine: 22136 which is 2 bytes of value.

Another example might be:

class A {};
class B {};

int main() 
{
	A * pA = new A;
	B * pB = reinterpret_cast<B*>(pA);
}


static_cast

static_cast can be used to force implicit conversions such as non-const object to const, int to double. It can be also be used to perform the reverse of many conversions such as void* pointers to typed pointers, base pointers to derived pointers. But it cannot cast from const to non-const object. This can only be done by const_cast operator.

The syntax is:

	static_cast < type-name > (expression)

It's valid only if type_name can be converted implicitly to the same type that expression has, or vise versa. Otherwise, the type cast is an error.

class Base {};
class Derived : public Base {};
class UnrelatedClass {};

int main() 
{
	Base base;
	Derived derived;

	// #1: valid upcast
	Base *pBase = static_cast<Base *>(&derived);  

	// #2: valid downcast
	Derived *pDerived = static_cast<Derived *> (&base);

	// #3: invalid, between unrelated classes
	UnrelatedClass *pUnrelated 
		= static_cast<UnrelatedClass *> (&derived);
}

In the example, the conversion from Base to Derived and Derived to Base are valid, but a conversion from Derived to UnrelatedClass is disallowed.

The #1 conversion here is valid because an upcast can be done explicitly. The #2 conversion, from a base-class pointer to a derived-class pointer, can't be done without an explicit type conversion. But because the type cast in the other direction can be made without a type cast, it's valid to use static_cast for a downcast. However, pDerivded would point to an incomplete object of the class and could lead to runtime errors if dereferenced.

As we saw in the example, static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived.

This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type.

Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.



dynamic_cast

dynamic_cast is used to perform safe downcasting, i.e., to determine whether an object is of a particular type in an inheritance hierarchy. It is the only cast that may have a significant runtime cost.

Look at the dynamic_cast of C++ Tutorial - dynamic_cast.





KeumKangKaChangOri



Full List of C++ Tutorials