Jump to content
  • Advertisement
Sign in to follow this  
Ccross

upcasting

This topic is 3509 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am learning C++ And Come to Upcastin and Downcasting.. Now can someone tell me what are the benefits of up-casting?

Share this post


Link to post
Share on other sites
Advertisement
Consider a function that moves the game camera forward. Now, consider a function that moves an opponent forward. Now, consider a function that moves a rocket forward. These three functions do the exact same thing to different objects. In order to avoid writing the same code three times for three different types, object-oriented languages provide up-casting: the "move forward" function does not need to know whether the object being moved is a camera, an opponent or a rocket, it only has to know that the object has a position (which will be changed) and a direction (to know what "forward" means).

And so, you would have a "SpatialObject" interface which provides position and direction, which would be implemented by cameras, opponents and rockets. You would then up-cast the camera, opponent or rocket to a spatial object and pass the result to the "move forward" function. This way, you only need one function to process all objects that can move forward.

Share this post


Link to post
Share on other sites
It's not so much that there's any benefit to doing it, more that it's possible and happens automatically if you have a function that takes a pointer or reference to a base class and you pass it the address of, or the instance of a derived class.

Edit: Too slow. And ToohrVyk's explanation is better [smile]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!