Bartlomiej Lewandowski
Bartlomiej Lewandowski

Reputation: 11180

Inheriting class with a function, with static members

I have a Bullet class that has a function draw(). It want to pass in a static member(object of a SDL_surface class) to this function but not sure how to do it correctly. my classes :

class AllyBullet: public Bullet
{

        public:

        static SDL_Surface *sprite;
};

class EnemyBullet: public Bullet
{

    public:

        static SDL_Surface *sprite;
};

void Bullet::Draw(SDL_Surface *screen)
{
    DrawSprite(screen,sprite,posX,posY);
}

Bullet does not have a sprite member. How can i write it so that it will know its for the classes that inherit it?

Upvotes: 0

Views: 141

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 477070

You can make the sprite virtual. Something like this:

struct Bullet
{
   virtual Sprite getSprite() const;
   void Draw(SDL_Surface * screen)
   {
      DrawSprite(screen, getSprite(), posX, posY);
   }
   // ...
};

struct  AllyBullet : public Bullet
{
   static Sprite s;
   virtual Sprite getSprite() const { return s; }
   // ... 
};

Upvotes: 1

piwi
piwi

Reputation: 5336

If Bullet is (or can be) abstract then you can have a pure virtual function:

struct Bullet
{
    SDL_Surface* get_sprite () = 0;
}

Then each inherited class implements this method. But if they all do the same work (and should all have a sprite) then sprite belongs to Bullet and could be accessed with the getter:

strut Bullet
{
    SDL_Surface* get_sprite () { return sprite; }
}

Upvotes: 0

Aaron McDaid
Aaron McDaid

Reputation: 27133

Bullet should specify a get_sprite() method, which must be implemented by AllyBullet and EnemyBullet:

class Bullet {
   virtual SDL_Surface * get_sprite() = 0;
}

which would be implemented as follows

   SDL_Surface * EnemyBullet :: get_sprite() { return sprite; }
   SDL_Surface * AllyBullet :: get_sprite() { return sprite; }

Then you can do

DrawSprite(screen,get_sprite(),posX,posY);

Upvotes: 0

Related Questions