Advertisement Jump to content
Sign in to follow this  
steenreem

Problems with classes

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

What I want to do in my code is this: Enemy *enemy = new BorgShip; printf("hitchance = %f",enemy->hit_chance); enemy = new KlingonShip; printf("hitchance = %f",enemy->hit_chance); So I have a pointer of type Enemy* but it can point do multiple classes like BorgShip and KlingonShip. Is this possible? So far I have this: struct Enemy { virtual static const float hit_chance =0; GLuint battletex; }; struct BorgShip: Enemy{ static const float hit_chance = 0.1; static GLuint battletex; BorgShip(){ battletex = borgshiptex; } }; struct KlingonShip: Enemy{ static const float hit_chance = 0.1; static GLuint battletex; KlingonShip(){ battletex = klingonshiptex; } };

Share this post


Link to post
Share on other sites
Advertisement
No - only methods can be virtual, not static or non-static members.


class Ship
{
public:
virtual ~Ship(){ }

virtual float HitChance() const=0;
};

class BorgShip : public Ship
{
public:
virtual float HitChance() const { return 0.5f; }
};

class KlingonShip : public Ship
{
public:
virtual float HitChance() const { return 0.8f; }
};

void f()
{
Ship *E=new BorgShip();
std::cout << E->HitChance() << std::endl;

delete E; // you had a memory leak in your code :)

E=new KlingonShip();
std::cout << E->HitChance() << std::endl;

delete E;
}


Note that this is illustrates the point but is a poor use of inheritance. If the HitChance is the only thing that varies, a simple member would suffice without inheritance. Alternatively, providing a Hit() method and doing the calculation in there would be a better approach.

HTH Paul

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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!