Kordnak
Kordnak

Reputation: 165

Call overloaded function from each object in std::vector

I'm working on my own menu system in OpenGL. What I want is to have all my objects that are related to the menu in one vector, so I could easily just loop them all like this:

for (auto i : menuObjects)
{
    i.checkInputs();
    i.draw();
}

I've tried with other looping methods, even having this->draw(); inside the base class' function, but that obviously ended up in an infinite loop.

My base class is basically this:

class menuObject
{
public:

    virtual void draw() { }
    virtual void checkInputs() { }

};

And inherited classes are like this:

class Button : public menuObject
{
public: 
    void draw()
    {
        ... drawing here ...
    }

    void checkInputs()
    {
        ... checking inputs here ...
    }

};

And here's how I save them in my vector:

std::vector<menuObject> menuObjects = {
    Button(... parameters here ...)
};

It never goes to the overloaded function. I would rather not have every different menu object in their own vector. Any ideas? <3

Upvotes: 0

Views: 144

Answers (1)

Gabriel
Gabriel

Reputation: 869

The issue you're having is that you cannot store objects of different types directly within a vector.

std::vector<menuObject> menuObjects = {
Button(... parameters here ...)
};

The above code slices the Button into a menuObject. Object slicing occurs when a derived class is value-assigned to the base class. Any information associated with the derived class is lost.

What you want to do is to use pointers to allow for polymorphism.

So your std::vector<menuObjects> would become either std::vector<menuObjects*> or vector<std::unique_ptr<menuObjects>. Use the latter if this vector is going to be responsible for managing the lifetime of menuObjects and the former if not.

Side note: if you do use the former option (i.e. raw pointers), make sure the remove invalidated pointers from the vector when the lifetime of a menuObject ends before the vector's lifetime ends.

Upvotes: 3

Related Questions