0

I've been working on a game, and I have a vector called 'people' of a class called 'Person'. The 'Person' class has the virtual method talk, which all of it's derived classes inherit. But when I call the function like so:

people.front().talk();

It call's it's parents class's function instead of the derived class's function. This makes perfect sense to me, because after all it's a vector of 'Person' instead of a vector of 'Bob'. I can't figure out how to avoid this issue, though. Here's some simplified code to show what I mean.

#include <iostream>
#include <vector>

using namespace std;

class Base {
    public:
        Base() {}
        virtual void coutLine() {cout << "base\n";}
};

class Derived : public Base {
    public:
        using Base::Base;
        void coutLine() {cout << "derived\n";}
};

class Owner {
    public:
        Base *baseItem;
        Dude() {}
};

int main() {
    vector<Base> stuffs;
    Derived d;
    stuffs.push_back(d);

    Owner chris;
    chris.baseItem = &stuffs.front();
    chris.baseItem->coutLine();
    return 0;
}
Merle
  • 81
  • 11
  • You are "slicing" the object - you need to store a pointer or reference to the object to be able to call virtual functions on the object. I'm 100% sure this is a duplicate question, I'll try to find another one. – Mats Petersson Mar 26 '17 at 00:09
  • There are probably more duplicates... – Mats Petersson Mar 26 '17 at 00:11
  • @MatsPetersson Wow... those are nearly exactly the same... that solved my problem immediately. My bad, I guess I didn't do my research before hand. Sorry internet! – Merle Mar 26 '17 at 00:15
  • @MatsPetersson wouldn't a better answer be that vector.push_back copy-constructs (or move-constructs in other cases) a Base object? The `push_back(const Base&)` will be passed the Derived object (as a reference to a Base), and `push_back` itself will call the copy constructor (with the reference to Base) AIUI. Where's the slicing part? – mgiuffrida Mar 26 '17 at 00:15
  • @mgiuffrida: You are correct, the slicing happens when the object is converted inside `push_back` - slicing is when you copy an object to a more basal form of itself - in this case `Base` - and `vector` stores a copy of the original object, using the `Base` form of it. For this sort of thing to work at all, the vector has to store a reference or pointer to the original object! – Mats Petersson Mar 26 '17 at 08:20

0 Answers0