Type Cast Operators

The C cast operator, in Bjarne Stroustrup's view, is too lax. For example, consider the following:

struct Data
{
    double data[200];
} ;

struct Junk
{
    int junk[100];
} ;
Data d = { 2.5e33, 3.5e-19, 20.2e32} ;
char * pch = (char *) (&d);   // typecast #1 – convert to string
char ch = char (&d);          // typecast #2 - convert address to a char
Junk * pj = (Junk *) (&d);    // typecast #3 - convert to Junk pointer

First, which of these three type casts makes any sense? Unless you resort to the implausible, none of them make much sense. Second, which of these three type casts are allowed? All of them are.

Stroustrup's response to this laxity was to add four type cast operators that provide more discipline for the casting process:

 dynamic_cast ...

Get C++ Primer Plus, Fourth Edition 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.