Archived

This topic is now archived and is closed to further replies.

Pointers to Base Classes

This topic is 5623 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 read the Battlecruiser thread, about passing different classes of ships to an Attack function by using as the parameter a pointer to the base class from which all types of cruisers inherit. I tried a similar thing in my code, but I''m having trouble. Here is some code: class CProjectile : public CSprite {...}; class CEnemy : public CSprite {...}; BOOL CProjectile::CheckForCollisionWith( CSprite* pOtherSprite ) { ... } And in the game loop: Projectile1.CheckForCollisionWith( &Enemy1 ); The problem is, when I try to access Enemy1''s data fields from the collision function, I get garbage values. What''s the deal? I use pOtherSprite->x_coord, and other stuff like that. Am I missing a step?

Share this post


Link to post
Share on other sites
Are the data elements in the function you are trying to access specific to CEnemy, or are they part of CSprite?

Assuming they are part of CSprite, it seems like it should work.

Are your shared data elements in CSprite declared ''protected''? I''m not sure how much of a difference that makes.

Try posting your actual declarations for CSprite, CEnemy and the code for CheckForCollisionWith().

Share this post


Link to post
Share on other sites
You''re probably either performing a dodgy cast or slicing an Enemy object. You really need to post a small compilable example of your problem.

Share this post


Link to post
Share on other sites
Hey, I solved the problem. I declared some of my data fields in CSprite AND in CEnemy. Apparently, when I passed the CEnemy object, its data fields were ignored, and the unitialized ones in CSprite were used. I just deleted my redeclarations and everything worked fine. Thanks for the replies!

Share this post


Link to post
Share on other sites