Tuesday, September 10, 2013

Converting data types - for example float to int

C++ produces warnings etc if you try and convert between data types - e.g. in something like int target = sqrt(number). However you can flag specific conversions to the compiler in the language.

This article explains why the preferred approach is to use is static_cast.

The explanation is rather obscure but seem to be related to the fact that what you are really doing is converting between different classes and while this is easy to understand between float and int for example could get more complicated at other times and there are some casting approaches that use some error checking - e.g. dynamic_cast. Well - at least that's my guess given the obscurity of the whole thing.

Syntax is here - with pointers to make things difficult:

MyClass *m = (MyClass *)ptr;
MyClass *m = static_cast<MyClass *>(ptr);
MyClass *m = dynamic_cast<MyClass *>(ptr);

No comments:

Post a Comment