Sign in to follow this  
steenreem

Problems with classes

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

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