c++ - Reading private member of base class through inherited function (?) -
in following example call d.run();
prints ad bd cd
, don't understand why. think should print ab bb cb ad bd cd
instead pushing vector vars_base
of base
6 times (?)
based on output seems me copy made of vars_base
member derived
class although private
base
(?)
i should clarify point of question merely understand behavour of example below - intention not access private members of base
through derived
.
#include <iostream> #include <vector> class base { private: std::vector<std::string> vars_base; protected: std::vector<std::string> &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 { }; 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; }
base b
, derived d
totally different objects , has no relationship each other.
the class blueprint of objects , not object itself. multiple instances of class having different memory areas.
to output want, can write code as
derived d; d.push_back("ab"); d.push_back("bb"); d.push_back("cb"); d.push_back("ad"); d.push_back("bd"); d.push_back("cd"); d.run();
Comments
Post a Comment