Let's say you're making a tile-based roll-playing game, and you're obsessed with OOP.
You have an abstract base class Tile
which will be inherited from by many derived classes, like Grass
Sand
and Water
The base class declares virtual methods for querying properties of derived classes, such as isCollidable()
and isFlammable()
class Tile{
public:
virtual constexpr bool isCollidable() = 0;
virtual constexpr bool isFlammable() = 0;
};
class Grass:
public Tile{
public:
constexpr bool isCollidable(){
return false;
}
constexpr bool isFlammable(){
return true;
}
};
class Sand:
public Tile{
public:
constexpr bool isCollidable(){
return false;
}
constexpr bool isFlammable(){
return false;
}
};
class Water:
public Tile{
public:
constexpr bool isCollidable(){
return true;
}
constexpr bool isFlammable(){
return false;
}
};
When you want a new type of Tile
you just create a new class, inherit from it, and implement it's virtual methods. Adversely, when you want a new property, you've to add is
methods to all the classes.
My question is, what is the cost of using polymorphism in this way? Is this an inappropriate use of polymorphism? If so, What are some alternatives to this while maintaining nice, pretty OOP?