c++ - Alternative to virtual variables -


i have 2 classes, base , derived. derived inherits base , additionally includes several functions , variables -- therefore need have 2 separate classes. however, share 1 function, run.

in example below have pass argument run in order execute read - argument depends on class object refers to. possible write generic version of read such program automatically uses vars_base or vars_derived depending on object calls run?

#include <iostream> #include <fstream> #include <string> #include <vector>  class base {   protected:     void read(std::vector<std::string>);    public:     void run(std::vector<std::string> vars) { read(vars); }     std::vector<std::string> vars_base; };  void base::read(std::vector<std::string> int_vars) {     (auto int_vars_it : int_vars)     {         std::cout << int_vars_it << "\n";     } }  class derived : public base {   protected:   public:     std::vector<std::string> vars_derived;     ///here other functions known derived, not base };  int main() {     base b;     b.vars_base.push_back("ab");     b.vars_base.push_back("bb");     b.vars_base.push_back("cb");     b.run(b.vars_base);      derived d;     d.vars_derived.push_back("ad");     d.vars_derived.push_back("bd");     d.vars_derived.push_back("cd");     d.run(d.vars_derived);      return 0; } 

is result want get?

class base { protected:     using vars_type = std::vector<std::string>;  private:     vars_type vars_base;  protected:     virtual vars_type& get_vars() {         return vars_base;     }  public:     void push_back(const std::string& str) {         get_vars().push_back(str);     }      void run()     {         (auto int_vars_it : get_vars()) {             std::cout << int_vars_it << " ";         }     } };  class derived : public base { private:     vars_type vars_derived;  protected:     vars_type& get_vars() override {         return vars_derived;     }  public:     ///here other functions known derived, not base };  int main(int argc, char* argv[]) {     base b;     b.push_back("ab");     b.push_back("bb");     b.push_back("cb");     b.run();    // prints ab bb cb      std::cout << std::endl;      derived d;     d.push_back("ad");     d.push_back("bd");     d.push_back("cd");     d.run();    // prints ad bd cd      return 0; } 

if explanation next: there no such thing "virtual variable", there virtual functions. can use virtual functions "internal accessors" member variables. although, derived class contains both vars_base , vars_derived, get_vars() lets override access appropriate instance of vars.

hope you'll find helpful.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -