C++ Type Casting

 C++
 

An introduction to C++ type casting.

(Declare: all code snippets in this post come from this)

Type Casting

Unrestricted explit type-casting allows to convert any pointer into any other
pointer type, independently of the types they point to. Which may make either
run-time error or unexpected behaviors.

In order to control type conversions between classes, We have four specific
casting operators: dynamic_cast, static_cast, reinterpret_cast and
const_cast. Their format is like dynamic_cast<new_type>(expression).

dynamic_cast

dynamic_cast performs run time check.

dynamic_cast can only be used with pointers and references to classes
(or with void*). Its purpose is to ensure that the result of the type conversion
points to a valid complete object of the destination pointer type.”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// dynamic_cast
#include <iostream>
#include <exception>

class Base {
virtual void dummy() {}
};

class Derived: public Base {
int a;
};

int main() {
try {
Base* pba = new Derived;
Base* pbb = new Base;
Derived* pd;

pd = dynamic_cast<Derived*>(pba); // downcast
if (pd == 0) {
std::cout << "Null pointer on first type-cast.\n";
}

pd = dynamic_cast<Derived*>(pbb); // downcast
if (pd == 0) {
std::cout << "Null pointer on second type-cast.\n";
}
} catch (exception& e) {
std::cout << "Exception: " << e.what();
}
return 0;
}

Only the first one is successful, because after type casting the first one is
pointing to a full object of class Derived, meanwhile, the second one is
pointing to an object of class Base, which is incompleted against Derived.

“When dynamic_cast cannot cast a pointer because it is not a complete object
of the required class, it returns a null pointer to indicate the failure. If
dynamic_cast is used to convert to a reference type and the conversion is not
possible, an exception of type bad_cast is thrown instead.

dynamic_cast can also perform the other implict casts allowed on pointers.

static_cast

static_cast performs compile time check.

static_cast can perform conversions between pointers to related classes, not
only upcasts (from pointer-to-derived to pointer-to-base),but also downcasts.
No checks are performed during runtime to guarantee that 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, it
does not incur the overhead of the type-safety checks of dynamic_cast.”

reinterpret_cast

const_cast

Remove or add const.

References

Type conversions

Casting in C++