I m a little bit confused about inheritence. I created an enemy class and calling enemies with a vector like this:
class enemy
{
public:
sf::RectangleShape rect;
float bottom, left, right, top;
sf::Texture enemytexture;
sf::Sprite enemysprite;
enemy(sf::Vector2f position, sf::Vector2f size, sf::Color color)
{
rect.setPosition(position);
rect.setSize(size);
rect.setFillColor(color);
enemytexture.loadFromFile("npc1.png");
enemysprite.setTexture(enemytexture);
}
void update(){
//////}
};
class goblin : public enemy
{
public:
goblin(sf::Vector2f position, sf::Vector2f size, sf::Color color);
void update()
{
enemytexture.loadFromFile("npc2.png");
enemysprite.setTexture(enemytexture);
};
};
std::vector<std::unique_ptr<enemy>> enemies1;
enemies1.emplace_back(std::unique_ptr<enemy>(
new enemy(sf::Vector2f(100, 100), sf::Vector2f(15, 10), sf::Color(255, 255, 255, 255))));
enemies1.emplace_back(std::unique_ptr<enemy>(new goblin::enemy(
sf::Vector2f(100, 100), sf::Vector2f(15, 10), sf::Color(255, 255, 255, 255))));
But i would like to draw different enemies and sprites like goblin etc. With this sample i draw only npc1.png for enemy and goblin classes. Is it possible to do that or do i need create another class? I searched some tutorials about inheritence but i cannot solve my problem. Plz i will appreciate for every suggestion or help.
CodePudding user response:
Add virtual
vefore void update
in enemy
; under the zero overhead principle, C does not implement dynamic dispatch unless you ask for it.
Also add virtual ~enemy()=default;
so the derived class data is properly cleaned up.
CodePudding user response:
class enemy
{
public:
/* snip */
// add a virtual dtor to the base class
virtual ~enemy() {}
// declare your base class methods as virtual
virtual void draw() {}
virtual void update() {}
};
class goblin : public enemy
{
public:
// and now in the derived class, you can overload
// the methods for that type
void draw() override {
// code to draw goblin
}
void update() override {
// code to update goblin
}
};
// all of your games enemies
std::vector<std::unique_ptr<enemy>> enemies1;
// now you can draw all of your enemies in one go
void drawAll() {
for(const auto& ptr : enemies1) {
ptr->draw();
}
}
// of update your enemies in one go
void updateAll() {
for(const auto& ptr : enemies1) {
ptr->update();
}
}