Inherited pointer problem

Started by
3 comments, last by Koen 16 years, 1 month ago
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
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]

Fruny: Ftagn! Ia! Ia! std::time_put_byname! Mglui naflftagn std::codecvt eY'ha-nthlei!,char,mbstate_t>

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.
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.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

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.

This topic is closed to new replies.

Advertisement