vendredi 28 mai 2021

Polymorphism and containers [duplicate]

I have a base class Drawable that serves as an interface and has several other classes that inherit from it. Now I want to create instances of those child classes and add them to a container so that i can iterate over them and call the draw function.

#include <vector>
#include <string>

struct Drawable
{
public:
    std::string name;
    virtual void draw() = 0;
    Drawable() = default;
    virtual ~Drawable(){};
    Drawable(Drawable &other) = default;
    Drawable(Drawable &&other) = default;
    Drawable &operator=(Drawable &&other) = default;
};

bool operator==(const Drawable &lhs, const Drawable &rhs)
{
    return lhs.name == rhs.name;
}

bool operator!=(const Drawable &lhs, const Drawable &rhs)
{
    return !(lhs == rhs);
}

struct Square : public Drawable
{
    std::string name;
    Square(std::string name)
    {
        this->name = name;
    }
    void draw()
    {
        /* Some logic*/
    }
};

int main()
{
    Square reddy("reddy");

    std::vector<Drawable> drawables;

    drawables.push_back(reddy);
}

I get this error message

error: 
      allocating an object of abstract class type 'Drawable'
            ::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);

Which happens because vector is trying to allocate space for a Drawable (which it can't because it's an abstract class). But how would i do this? None of the tutorials on polymorphism that i found covered something like this. Or am I searching for the wrong thing?

Aucun commentaire:

Enregistrer un commentaire