Casting
Introduction
Casting involves converting one type to another. Some casts are valid and others may not be valid. We have the old style "C" style cast and the new casts: static_cast, dynamic_cast, const_cast, reinterpret_cast.File: cast1.cpp
#include <iostream> using namespace std ; int main() { int x1 = 10; float f1 = 10.5 ; x1 = (int)(f1); cout << "x1:" << x1 << endl ; //Undefined behavior //Not recommended const int x2 = 11 ; int* ptr1 = (int*) &x2 ; *ptr1 = 12 ; cout << "x2:" << x2 << endl ; } Output: $ rm a.exe ; g++ cast1.cpp ; ./a.exe 10 This is the old style "C" way of casting. It is better to use the new casting style as there is more compiler checking and it's easier to make out what the cast is doing. The "C" style could be a "static_cast" or a "reinterpret_cast" but it's hard to tell just from looking at the code.
File: cast2.cpp
#include <iostream> using namespace std ; class A { public: int x1 ; }; class B : public A { public: int x1B ; }; class C : public A { public: int x1C ; }; int main() { B bObject ; bObject.x1B = 22 ; A* aObject = &bObject ; //Not safe. as aObject contains bObject as the //underlying object C* cObject = (C*)aObject ; cout << cObject->x1C << endl ; } $ rm a.exe ; g++ cast2.cpp ; ./a.exe x1:10 22 The above shows another danger with the old style cast. B bObject ; bObject.x1B = 22 ; A* aObject = &bObject ; //Not safe. as aObject contains bObject as the //underlying object C* cObject = (C*)aObject ; cout << cObject->x1C << endl ; The compiler allows the above code and it also runs fine. However "aObject" is a "B" type object and not a "C" object. The better way to handle such casts is using "dynamic_cast" .