Problem with vector of objects/pointers (Implementing composite design pattern)
<p>I'm trying to implement the composite design pattern for a uni practical, I have an abstract base class DocumentComponent, and two classes that inherit from it, TextBody and Word. It's supposed to represent a sentence that can contain additional sentences and/or words. My problem arises when I try to implement the TextBody class, which has functions addComponent and Print. They are supposed to add a new DocumentComponent object to the vector using push_back, and to call the print function of each element in the vector, respectively. I'm storing my objects in a vector of DocumentComponent objects/pointers called container, and I can only get one of the two to work at a time (by changing my vector to either be a vector of pointers or a vector of objects). If I do the former my print function works but not my addComponent function, and if the latter the situation is reversed. Here's my code:</p>

<p>documentComponent.h:</p>

<pre><code>class DocumentComponent
{   
    public:
     virtual void removeComponent(int index){}
     virtual void addComponent(DocumentComponent&amp; comp){}
     virtual void print()=0;
};
</code></pre>

<p>textBody.h:</p>

<pre><code>class TextBody : public DocumentComponent
{
    public:
        TextBody();
        virtual void addComponent(DocumentComponent&amp; comp);
        virtual void print();
    private:
        vector&lt;DocumentComponent*&gt; container;
};
</code></pre>

<p>textBody.cpp:</p>

<pre><code>void TextBody::addComponent(DocumentComponent&amp; comp)
{
    container.push_back(&amp;comp);
}

void TextBody::print()
{
    if (container.size() == 0)
     return;
    for_each(container.begin(), container.end(),mem_fun_ref(&amp;DocumentComponent::print));
}
</code></pre>

<p>I get the error message</p>

<p>"Cannot initialize 'DocumentComponent &amp;' with 'DocumentComponent *' in function for_each

<p>which I understand is because I'm giving it a pointer when it wants a reference, but changing my vector to a vector of objects results in</p>

<p>"Cannot create instance of abstract class 'DocumentComponent'"</p>

<p>in my addComponent function</p>
