c++ - How do inherited classes access data stored in a base class container? -


i'm trying access data base class container multiple inherited classes. i've looked other stackoverflow questions on either static vectors , shared_ptr or unique_ptr i'm not sure these best way forward (and i'm unfamiliar how implement shared_ptr or unique_ptr). please see code below.

class event { public:   event(){}   virtual ~event(){}   std::vector<int>& testdata() {return test;} // return reference. private:   std::vector<int>test;  };  class inheritedevent1 : public event { public:   void firstmethod(void); };  class inheritedevent2 : public event { public:   void secondmethod (void); };  void inheritedevent1::firstmethod(void){ testdata().push_back(1); // insert data event vector. std::cout << "firstmethod: size " << testdata().size() << std::endl; }  void inheritedevent2::secondmethod(void){ std::cout << "secondmethod: size " << testdata().size() << std::endl; }  int main() { inheritedevent1 first; inheritedevent2 second; first.firstmethod(); second.secondmethod(); } 

in example specifically, both of methods attempt access same vector yet appear creating / accessing own copy of container. , suggestions appreciated.

i assume want of inherited classes share same vector. in case, static vector in base class make sense.

as did not describe exact problems encounterd, can imagine not initializing static data member properly.

here implementation above prints 1 each call.

#include <iostream> #include <vector> using namespace std;  class event { public:   event(){}   virtual ~event(){}   std::vector<int>& testdata() {return test;} // return reference. private:   static std::vector<int> test;  }; std::vector<int> event::test;   class inheritedevent1 : public event { public:   void firstmethod(void); };  class inheritedevent2 : public event { public:   void secondmethod (void); };  void inheritedevent1::firstmethod(void){ testdata().push_back(1); // insert data event vector. std::cout << "firstmethod: size " << testdata().size() << std::endl; }  void inheritedevent2::secondmethod(void){ std::cout << "secondmethod: size " << testdata().size() << std::endl; }  int main() { inheritedevent1 first; inheritedevent2 second; first.firstmethod(); second.secondmethod(); } 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -