Amine Amine - 1 month ago 7
C++ Question

Trying to push_back into a vector pointing to an abstract class

Compiling my code that contains this class:

class Dessin
{
private:
vector<Figures*>T;
public:
void ajouteFigure(const Figures& f) const
{
for(auto element: T)
{
T.push_back(f);
}
}
};


yields an error:


[Error] no matching function for call to
'std::vector::push_back(const Figures&) const'


This is what I'm supposed to do in the main()

Dessin s;
s.ajouteFigure(Cercle(1.1));


Why wouldn't this work?

Answer

Assuming Cercle is a class name, you're trying to push a value where a pointer is expected.

To "fix" the error you should change your ajouteFigure prototype to accept Figures pointers and non-const this:

void ajouteFigure(Figures* f) 

Then you should call it passing a pointer to a Figures object, i.e. created with a new expression:

s.ajouteFigure(Cercle(1.1));

That being said, this code seems pointless. You're adding the pointer as many times as you have elements in the vector (which is always 0 in the example you provided).

Using raw pointers is also unadvised, you should use smart pointers like std::unique_ptr, although that would break the current code.

Consider this, less improper, example:

class Dessin
{
    private:
        vector<unique_ptr<Figures>> T;
    public:
        void ajouteFigure(unique_ptr<Figures> f)
        {
            T.push_back(move(f)); // just once
        }
};

and at the call site:

Dessin s;
s.ajouteFigure(make_unique<Cercle>(1.1)); // C++≥14

or, if you can't use C++14:

Dessin s;
s.ajouteFigure(unique_ptr<Figures>(new Cercle{1.1}));