Inheritance going wrong

I'm working on a simple game framework based on SDL2.
I have two base class types;
- item (which is anything that can be drawn on screen)
- group (which is a group of item pointers stored in a vector; calling draw on a group draws all items in that group, calling update updates all, etc...)

So, I have classes falling from there that inherit from "item" such as my soldier class for a Risk clone. In soldier, I overwrite the update function so that it draws both a background square, and a number on top. I shoved those soldiers in a "group" called board_1, and called update and draw on the group.

Now, what apears to be happening is the item version of update() is being called instead of the soldier version when called from a group.
If I take the soldier itself and call update, then the correct one is called (local one from soldier class).
If I return a pointer to the soldier saved in group and call update on that pointer, then the item version is called instead.

Why is my soldier class being ignored/overwritten by the parent class if I add it to a group?
- Is the soldier being cast back to an item?

How might I fix this?
Last edited on
Maybe your item class doesn't have virtual functions?

Ah, thank you Thomas1965.

I had the wrong idea about how virtual functions worked so I didn't even consider them.
Thanks for pointing me right.

First google result:
https://www.geeksforgeeks.org/virtual-function-cpp/

Edit:
Just going a little further in, it's probably a good idea to use a virtual destructor as well.
https://www.geeksforgeeks.org/virtual-destructor/
Last edited on
Topic archived. No new replies allowed.