lundi 27 février 2017

The data types the 4 different casts can take (or normally take) in c++

It seems static_cast take could take value, reference or pointer and convert them to another type of value, reference or pointer. for instance: value:

B* pb; D* pd;
pointer:D* pd2 = static_cast<D*>(pb);   // Not safe, D can have fields and methods that are not in B.

However, it is not safe for static_cast to take pointer as input because the pointer could not be compatible with the pointer type converted to.

Seems dynamic_cast and reinterpret_cast can only take reference and pointer. Not sure what will happen if use dynamic_cast and reinterpret_cast on value types:

int B; char D;
B = dynamic_cast<B>(D);

int B; char D;
B = reinterpret_cast<B>(D);

I know for cont_cast, it only take pointer or reference but not variable which is undefined behavior.

Aucun commentaire:

Enregistrer un commentaire