Jump to content
  • Advertisement
Sign in to follow this  
suliman

Inherited pointer problem

This topic is 3851 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

Hi Using c++ and mvc++ 2005 i have a unit class and inherited from it a have ship and aircraft class like so class aircraft:public unit Now, my player has a (unit * theUnit) to keep track of the currently controlled unit, which can be both ship and aircrafts. But if i wanna get hold of the ship-specific data from this pointer doing this: ship * s=(ship *)theUnit; It compiles fine, but the ship-data s points to is corrupted, while the unit-specific data s points to is the real stuff. How to solve this? Thanks Erik

Share this post


Link to post
Share on other sites
Advertisement
That sounds like a slicing problem.

How exactly do you create the new object and assign the pointer?

Make sure you do work with pointers, you can't do that with a "true" (as in non pointed to) object.

@SiCrane: Thanks for correcting, i had written shearing instead of slicing.

[Edited by - Endurion on March 7, 2008 11:42:21 AM]

Share this post


Link to post
Share on other sites
I think you mean slicing problem. Alternately, it could just be the case that you're casting a pointer to an object that isn't actually a Ship to a Ship pointer.

Share this post


Link to post
Share on other sites
Quote:
Original post by suliman
Now, my player has a (unit * theUnit) to keep track of the currently controlled unit, which can be both ship and aircrafts. But if i wanna get hold of the ship-specific data from this pointer doing this:

ship * s=(ship *)theUnit;

A good way out of this would be to refactor your code so that all the data needed is provided by the unit base-class, or by polymorphic functions declared in the base-class.

Share this post


Link to post
Share on other sites
Also, if you replace your casting code with

ship* s = dynamic_cast<ship*>(theUnit);

it might be easier to test what SiCrane said. Dynamic casting is "safer" because if the cast fails (because theUnit is not actually pointing to a ship), s will be a null-pointer, which you can check for.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!