I'm quite new to C++ and I am trying to store objects inside a std::vector like this:
Event.h:
//event.hclass Event{public: Event(); Event(std::string name); ~Event(); void addVisitor(Visitor visitor);private: std::vector<Visitor> m_visitors;};
Event.cpp:
//event.cppEvent::Event() : m_name("Unnamed Event"){}Event::Event(std::string name) : m_name(name){}void Event::addVisitor(Visitor visitor){ this->m_visitors.push_back(visitor);}void Event::listVisitors(){ std::vector<Visitor>::iterator it; for(it = this->m_visitors.begin();it != this->m_visitors.end(); ++it) { std::cout << it->getName() << std::endl; }}
Visitor.h:
//visitor.hclass Visitor{ public: Visitor(); Visitor(std::string name); ~Visitor(); std::string getName() const; void listVisitors(); private: std::string m_name;};
Visitor.cpp:
//visitor.cppVisitor::Visitor() : m_name("John Doe"){}Visitor::Visitor(std::string name) : m_name(name){}std::string Visitor::getName() const{ return m_name;}
main.cpp:
//main.cppint main(){ Event *e1 = new Event("Whatever"); Visitor *v1 = new Visitor("Dummy1"); Visitor *v2 = new Visitor("Dummy2"); e1->addVisitor(*v1); e1->addVisitor(*v2);}
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 std::vector<std::unique_ptr<Visitor> > m_visitors
, 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?