tags:

views:

87

answers:

1

Hi, i'm new to c++ and having a little problem understanding about c++'s casting.

According to "C++ Primer", the old style cast is like: int(variable) or (int) variable, and new ones introduced by c++ standard includes static_cast<>, const_cast<>, reinterpret_cast<> and dynamic_cast<>.

  1. Is the static_cast<> equivalent to "old style cast" ?

  2. I think that isn't it if I consider basic data types (int, double...) as a class, then it would be convinient to use just int(object) to do the casting ? Does the standard c++ implement basic types as a class?

+8  A: 

1. Old style cast is equivalent of different casts:

int i;
double d = 3.14;
i = static_cast<double>(d); //(double)d;
const char* p = reinterpret_cast<char*>(&d); //(char*) &d;
char* q = const_cast<char*>(p); //(char*) p;

2. Basic data types are not classes (e.g you can't inherit from them) but they support the constructor syntax for uniformity.

int i(10); //same as int i = 10

To do conversions between basic types, you can indeed use this syntax (static_cast stands out more, though).

UncleBens
Just a clarification - the old style casts do different jobs in different cases. Sometimes they translate values, sometimes they just relabel the same bit pattern with a different type, sometimes they just add/remove type modifiers like "const". In templates in particular, this can be a problem, as the template programmer needs to specify the right behaviour but doesn't necessarily know which types are involved. The C++ casts specify more precisely what is intended, and are much less prone to problems in templates.
Steve314