Search code examples
c++qtdesign-patternsreferencecomposite

Composite in C++ error [no matching member function to callto 'push_back']


Hi trying to do a simple composite and i am struggling with an error when trying to add one Compenent to the composite for training

Here is the code

Component interface Inteface for drawing composite

class ObjectInterface
{
public:
ObjectInterface() {}
virtual void draw()=0;
virtual void applyTranslation(float x,float y){}
virtual void applyRotationDirect(float angle){}
virtual void applyRotationIndirect(float angle){}
virtual void applyHomethety(float ratio){}
virtual void applyAxialSymmetry(){}
virtual void applyCentralSymmetry(){}
};


One element - Line

class Line : public ObjectInterface,Object2D
{
public:
    Line(string color,Point p1,Point p2);
    // Inherited method from Object2D
    float getArea();
    float getPerimeter();

    // Inherited method from ObjectInterface
    virtual void draw();
    void applyTranslation(float x,float y);
    void applyRotationDirect(float angle);
    void applyRotationIndirect(float angle);
    void applyHomethety(float ratio);
    void applyAxialSymmetry();
    void applyCentralSymmetry();

    friend ostream& operator<< (ostream &os, const Line &p);
 };


class Fresque : public ObjectInterface
{
public:
    Fresque();
    // Inherited method from ObjectInterface
    void draw();
    void applyTranslation(float x,float y);
    void applyRotationDirect(float angle);
    void applyRotationIndirect(float angle);
    void applyHomethety(float ratio);
    void applyAxialSymmetry();
    void applyCentralSymmetry();

    // Personal method
    bool add(ObjectInterface const &o);
    bool remove(ObjectInterface const& o);

private:
    std::vector<ObjectInterface*> objects;  // CONTAINER FOR COMPOSITE
 };

cpp file for the add method

bool Fresque::add(ObjectInterface const & o){
  objects.push_back(o);  //===> THE ERROR HERE
return true;
}

the Error :

/fresque.cpp:50: erreur : no matching member function for call to 'push_back' objects.push_back(o); ~~~~~~~~^~~~~~~~~

The IDE is QT , i feel bad not knowing where the mistake is and I am pretty sure it's an obvious one :/.


Solution

  • std::vector<ObjectInterface*> is a vector of pointers to ObjectInterfaces. o is an ObjectInterface, not an ObjectInterface* (pointer to ObjectInterface), so you need to get the address of o:

    objects.push_back(&o);