Casting is one of the most troublesome operations in C/C++ as when you use casts you are directing the compiler to trust you and to forget about type checking. Casts should be used as infrequently as possible and only when there is no alternative. We have two main terms for casting, upcasting and downcasting. Upcasting is casting from a derived class to one of its base classes and downcasting is casting from a base class to one of its derived classes. Remember that the inheritance tree branches down with the base class at the top. We also have the lesser known cross-casting for casting a class to a sibling class. C++ introduces new explicit casts that identify the rationale behind the cast, clearly identifies that a cast is taking place and confirms type-safe conversions. These casts are:
Here is an example of all four casts: 1 2 // Start reading from main() function to help make it easier to understand 3 #include <iostream> 4 using namespace std; 5 6 // Demo classes with a virtual base class 7 class Account { 8 public: 9 float balance; // for demonstration only! 10 virtual ~Account(){} 11 }; 12 class Current: public Account {}; 13 class Test { public: float x, y;}; 14 15 // Demo Function 16 void someFunction(int& c) 17 { 18 c++; // c can be modified 19 cout << "c has value " << c << endl; //will output 11 20 } 21 22 int main() 23 { 24 float f = 200.6f; 25 // narrowing conversion, but we have notified the compiler 26 int x = static_cast<int>(f);The output of this code is: C:\My Documents\My Teaching\OOP Notes\EE553_Output\cpp>casting 200 These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way. |