Chapter 44. Casts

Difficulty: 6

How well do you know C++'s casts? Using them well can greatly improve the reliability of your code.

The new-style casts in standard C++ offer more power and safety than the old-style (C-style) casts. How well do you know them? The rest of this problem uses the following classes and global variables:

class  A { public: virtual ~A(); /*...*/ }; 
A::~A() { }

class B : private virtual A  { /*...*/ };

class C : public  A          { /*...*/ };

class D : public B, public C { /*...*/ };

A a1; B b1; C c1; D d1;
const A  a2;
const A& ra1 = a1;
const A& ra2 = a2;
char c;

This Item presents four questions.

  1. Which of the following new-style casts are not equivalent to a C-style cast?

    const_cast 
    dynamic_cast
    reinterpret_cast
    static_cast
    
  2. For each ...

Get Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.