0

I am trying to code a game for fun and I've run into a problem that I am kind of stuck on. I have 2 classes, baseTile(parent) and caveBasic(derived), I want to call a function of my derived class when I only have a parent-class-pointer. They look like this, the init function is just supposed to chose a random value for graphicRect from 0-3 for the parent and 4-7 for the derived class:

    class baseTile
{
public:
    unsigned short graphicRect = 0;
    baseTile(){
        ;
    }
    virtual void init() {

        graphicRect = (rand()) % 4;
        return;
    }
};

And

class caveBasic :
    public baseTile
{

public:
    caveBasic() {
        ;
    }

    void init() {
        graphicRect = (rand()) % 4;
        graphicRect += 4;
        return;

    }
};

And then in another class, I put a lot of objects from the derived class into a vector of the parent class. When I then try to access them and call init(), the parent implementation is called. I created a function getTileAt, to chose the correct object from my vector:

inline baseTile* getTileAt(int w, int h) {
    return &map[w + h * GRID_WIDTH];                       //map type is std::vector<baseTile>
}

This is used here, where the wrong implementation is called:

this->map = {};                                              
this->map.reserve(GRID_HEIGHT * GRID_WIDTH);
for (int i = 0; i < GRID_HEIGHT * GRID_WIDTH; i++) {
    caveBasic newT;
    this->map.push_back(newT);
}

baseTile* curr;
curr = getTileAt(2, 2);         
curr->init();                                             //here, the parent implementation is called
                                                          //and thus graphicRect < 4 afterwards

I would expect the derived implementation to be called here, since the parent implementation is virtual, but it does not work. Any idea what I'm missing here? Thanks in advance

Saetch
  • 1
  • 1
  • Your vector is storing `baseTile` objects, so you are [slicing](https://stackoverflow.com/questions/274626/) every derived object you try to put in the vector. You need to store `baseTile*` pointers instead, and create the derived objects using `new` – Remy Lebeau Nov 21 '21 at 20:07

0 Answers0