Avoid overwriting all the methods in the child class
- by Heckel
The context
I am making a game in C++ using SFML. I have a class that controls what is displayed on the screen (manager on the image below). It has a list of all the things to draw like images, text, etc. To be able to store them in one list I created a Drawable class from which all the other drawable class inherit.
The image below represents how I would organize each class. Drawable has a virtual method Draw that will be called by the manager. Image and Text overwrite this method.
My problem is that I would like Image::draw method to work for Circle, Polygon, etc. since sf::CircleShape and sf::ConvexShape inherit from sf::Shape. I thought of two ways to do that.
My first idea
would be for Image to have a pointer on sf::Shape, and the subclasses would make it point onto their sf::CircleShape or sf::ConvexShape classes (Like on the image below). In the Polygon constructor I would write something like
ptr_shape = &polygon_shape;
This doesn't look very elegant because I have two variables that are, in fact, just one.
My second idea
is to store the sf::CircleShape and sf::ConvexShape inside the ptr_shape like
ptr_shape = new sf::ConvexShape(...);
and to use a function that is only in ConvexShape I would cast it like so
((sf::ConvexShape*)ptr_shape)->convex_method();
But that doesn't look very elegant either. I am not even sure I am allowed to do that.
My question
I added details about the whole thing because I thought that maybe my whole architecture was wrong. I would like to know how I could design my program to be safe without overwriting all the Image methods.
I apologize if this question has already been asked; I have no idea what to google.