Search This Blog

Sunday, January 07, 2007

Casting

Peace be upon you

when I was checking the code of Notepad++, I found something stops me, "reinterpret_cast",
first of all i never had the need to know much about casting because I use so stuff like

float BigNumber=15.12;
int T = (int)BigNumber;

anyways, when I start looking for this keyword I found it's amazing, there is a lot of ways of casting that make life more easier and more cool and more safe, here is the types of casting that I have found

- dynamic_cast
- static_cast
- const_cast
- reinterpret_cast
- safe_cast

every one do something cool, I will explain as I understand and for more details you can visit this link
http://msdn2.microsoft.com/en-us/library/5f6c9f8h.aspx

- dynamic_cast
used with the casting objects, when it find that the object is not identical with the Type, it return null, I call this Safe casting, this protect your application from being crashed if you are casting objects that don't has the same type.

- static_cast
this type of casting I call unsafe casting, why because it just convert the pointer to the object type without regarding the original type of the object or the type, imagine that
Car *CarObj;
Bus *BusObj;
Bus *NewCarObj= static_cast(CarObj);
what just happen can cause a lot of troubles while you are running your application, why , simply you reference pointer to object not the same type, this why it's not safe and can cause troubles

- const_cast
this one is cool, suppose we have const varible, and for some reason you want to change it, use this casting operator it will do it for you.

- reinterpret_cast
this casting is used to convert the object address into integral type variable, this cast is not safe to use with casting objects back

- safe_cast
this one is for dot net guys so I am not going to talk about :D,

I think the best 2 casting operators here is ( dynamic_cast - const_cast )

guys you can read more about it, but I mentioned it because I think it's important to know such things specially C++ Developers,

thanks for reading this, please if you find anything not right please post reply and tell me :)

No comments:

There was an error in this gadget