Deep Dive into CPP: Type Casting operators

(int) x – c style casting
int(x) – cpp style
static_cast<int>x – new cpp style looks like a template casting.

C style casting is always dangerous.

class Account
{
double bal;
public:
double getBalance()
{
return bal;
}
};
Account acc = new Account(1000);
acc.bal = 100000; //  error cant access private variable.

But,

double *p = (double*) &acc
*p = 1000000; // now bal will be changed.

Because the 1st statement will be reinterpreted as

Double *p = reinterpret_cast<double*> (&acc)

Which the compiler moves the line to runtime, where reinterpret cast will simply assign the address of the class to the destination. Which now points to the bal variable which is at first. Now you can change. Now, many can ask, we can use directly the reinterpret_cast to change the values in private variables. But that will happen with the programmers consent, but here it happens without his knowledge which is dangerous. Therefore, use reinterpret_cast with utmost care.
There are 4 types of static_cast,dynamic_cast,reinterpret_cast and const_cast.

  • static_cast can perform conversions between pointers to related classes, not only upcasts (from pointer-to-derived to pointer-to-base), but also downcasts (from pointer-to-base to pointer-to-derived). 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.
  • 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.
  • reinterpret_cast will compare bit by bit to find any similarities between source and destination during runtime. But it ends up just assigning the value to the destination. reinterpret_cast should be used by the user with caution.
  • const_cast manipulates the constness of the object pointed by a pointer, either to be set or to be removed.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s