Sign in to follow this  
Ccross

upcasting

Recommended Posts

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this