Skip to main content
gamedev.net
🔒 Locked

type casting

Started by KSP 1 reply 800+ views
Original Post
KSP
KSP
Hi everyone, I had a question: What is the difference between static_cast, dynamic_cast and casting directly (e.g. using "Parent * p = (Parent*)child;")? Yours, KSP
Huskey
Huskey
I guess a quick look on google would do the trick :P
But - not to be unhelpful - here's what i read about it:

explicit conversion (b = (int) a)- The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors.

dynamic_cast - can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

static_cast - static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe.

Hope that's the answer to your question. (In case anything here is wrong - let me know pls)

Huskey
ToohrVyk
ToohrVyk
Quote:
Original post by KSP
Hi everyone,
I had a question: What is the difference between static_cast, dynamic_cast and casting directly (e.g. using "Parent * p = (Parent*)child;")?


Unless you're using multiple inheritance, all of these will do the same thing, and so will implicit casting (Parent* p = child;)

static_cast is a cleaner alternative to C-style casts whenever a cast is necessary, because it explains what the cast does (it doesn't reinterpret the value without changing it, and it doesn't alter const-volatile qualifiers without touching the value: it changes the value to a new type).

dynamic_cast is used for the reverse casting (Child *c = dynamic_cast<Child*>(parent);) because it's safe: if the base class pointer did not really reference a derived class instance, the resulting pointer will be null (which can then be tested).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.