Problems with classes

Started by
0 comments, last by Aardvajk 15 years, 9 months ago
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; } };
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

This topic is closed to new replies.

Advertisement