How to polymorphically call function overloads in different derived classes? [duplicate]

  2d-games, c++, inheritance, polymorphism, stdvector

I’m building a 2D platformer game, and every entity in my game inherits from class Entity. I have a std::vector<std::unique_ptr<Entity>> entities to dynamically allocate these entities. I want to also polymorphically check for collision from the driver code:

for(int i = 0; i < entities.size();i++){
    for(int j = 0; j < entities.size();j++)
    entities[i]->checkCollision(*j);
}

The derived types include Player, Enemy, Tile etc. The collision is handled differently between different derived types, that’s why I want to use polymorphism. My approach so far:

 struct Entity{
 virtual void checkCollision(Entity&e){};
 };

 struct Player : public Entity{
 void checkCollision(Tile &t) override { //collision with tile};
 void checkCollision(Enemey &e) override {//enemy colliion};
 };

The virtual function however isn’t overriden, and the code fails to compile. Is there a sensible way to achieve this, or is my polymorphic approach fundementally flawed?

Source: Windows Questions C++

LEAVE A COMMENT