O'Reilly logo

C++ Primer Plus, Fourth Edition by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required