Discussion of the C++ casting

Old C Casts

There are several problems with old type C casts. First, the syntax is the same for every casting operation. This means it is impossible to tell the purpose of the cast

Another problem is finding all the casts in a large file. Parentheses with an identifier between them are used throughout C and C++ programs. There is no easy way to search a source file and get a list of all the casts being performed.

Another problem with the old C cast is that it allows you to cast practically any type to any other type. This allows you to circumvent the safety of type checking. Using the new C++ style casting operators will make your programs more readable (easier to maintain) and less error-prone.

C++ Casts

The casts consist of:


convert one type to another type


to remove the constant nature of a type


for navigation of an inheritance hierarchy


 perform type conversions on un-related types


All of the casting operators have the same syntax and are used in a manner similar to what we will see later in the course when we cover templates.

 static_cast is the most general and is intended as a replacement for most C-style casts.  const_cast is used to remove the const from a type. The other two forms are for specific circumstances that should be researched when or if they are encountered.

 An example of a static_cast is one that can perform arithmetic conversions, such as from int to double. To avoid integer truncation in the following computation:

  int num = 7;

  int denom = 3;

  double fraction = 7/3;

   double rate = static_cast<double>(num)/denom;

Bottom line... While you need a basic understanding of these casts, you can get through this course without mastering all aspects of all of these types of casts.