Avoid overwriting all the methods in the child class

Posted by Heckel on Game Development See other posts from Game Development or by Heckel
Published on 2014-05-26T19:20:29Z Indexed on 2014/05/26 22:06 UTC
Read the original article Hit count: 263

Filed under:
|
|
|

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.

enter image description here

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.

enter image description here

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.

enter image description here


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.

enter image description here


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.

© Game Development or respective owner

Related posts about architecture

Related posts about sfml