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<>.
Is the static_cast<> equivalent to "old style cast" ?
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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With