Note that there are some explanatory texts on larger screens.

plurals
  1. POTrying to store objects in a vector
    text
    copied!<p>I'm quite new to C++ and I am trying to store objects inside a std::vector like this:</p> <p>Event.h:</p> <pre><code>//event.h class Event { public: Event(); Event(std::string name); ~Event(); void addVisitor(Visitor visitor); private: std::vector&lt;Visitor&gt; m_visitors; }; </code></pre> <p>Event.cpp:</p> <pre><code>//event.cpp Event::Event() : m_name("Unnamed Event") { } Event::Event(std::string name) : m_name(name) { } void Event::addVisitor(Visitor visitor) { this-&gt;m_visitors.push_back(visitor); } void Event::listVisitors() { std::vector&lt;Visitor&gt;::iterator it; for(it = this-&gt;m_visitors.begin();it != this-&gt;m_visitors.end(); ++it) { std::cout &lt;&lt; it-&gt;getName() &lt;&lt; std::endl; } } </code></pre> <p>Visitor.h:</p> <pre><code>//visitor.h class Visitor { public: Visitor(); Visitor(std::string name); ~Visitor(); std::string getName() const; void listVisitors(); private: std::string m_name; }; </code></pre> <p>Visitor.cpp:</p> <pre><code>//visitor.cpp Visitor::Visitor() : m_name("John Doe") { } Visitor::Visitor(std::string name) : m_name(name) { } std::string Visitor::getName() const { return m_name; } </code></pre> <p>main.cpp:</p> <pre><code>//main.cpp int main() { Event *e1 = new Event("Whatever"); Visitor *v1 = new Visitor("Dummy1"); Visitor *v2 = new Visitor("Dummy2"); e1-&gt;addVisitor(*v1); e1-&gt;addVisitor(*v2); } </code></pre> <p>If I do it like this I would have to add a copy constructor which would make a deep copy so the object gets copied properly into the vector. I'm looking for a way around it by only storing pointers to the objects in a vector. I already tried it with <code>std::vector&lt;std::unique_ptr&lt;Visitor&gt; &gt; m_visitors</code>, but then I got some errors when calling addVisitor in main.cpp. Of course I changed the declaration of the class members accordingly. How would an appropriate declaration of the members and the member function look like to make it work?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload