-3

Alright, I'm trying to call a function from a class in C++ what overides a function from its parent class.

The class is setup:

BaseClass that has the update function declared publicly like this:

virtual void update() = 0;

Then I have the Object class what extends the BaseClass. In this class I declare update again by doing:

virtual void update() override;

Then I have my Player class what has its update function declared like this:

void update() override;

I then store a vector of object and loop through it the vector is declared:

std::vector<Object> _objs

Do I have to create a new vector to loop through to call the right update function or is there some sort of way I can call the right update function when im looping through a array of object?

Biffen
  • 6,249
  • 6
  • 28
  • 36
Oisin100
  • 13
  • 2
  • 4
    Instead of describing the class setup, why don't you just show us some code? – PC Luddite Sep 19 '15 at 17:10
  • One line of code explains more than hundred lines of prose in most cases. – πάντα ῥεῖ Sep 19 '15 at 17:11
  • possible duplicate of [Making a vector of instances of different subclasses](http://stackoverflow.com/questions/10338548/making-a-vector-of-instances-of-different-subclasses) – Biffen Sep 19 '15 at 17:14
  • It will automatically call the correct override function. That's what overrides are for. – QuentinUK Sep 19 '15 at 17:16
  • 1
    @QuentinUK No it won't, because of slicing. – Biffen Sep 19 '15 at 17:17
  • Welcome to stackoverflow.com. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). You might also want to learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Sep 19 '15 at 17:19
  • @Biffen That can be fixed by using a vector of pointers std::vector _objs should be std::vector _objs – QuentinUK Sep 20 '15 at 23:42

1 Answers1

0

You need to use either a vector of pointers

std::vector<Object*>

or smart pointers

std::vector<std::shared_ptr<Object>>

If you don't, adding a Player object to the vector will result in object slicing. Player will be converted to Object, so Object's implementation of update() will be called instead.

PC Luddite
  • 5,883
  • 6
  • 23
  • 39