c++ - How to use a member variable in a base class function when its size is only known to the derived class -
i want implement function in baseclass uses members of derived classes. each derivedclass, have member of different value. here's example. baseclass
has member function foo()
uses variable arrstr
. content of nul terminated char array found in derived class. how can make baseclass
"know" variable arrstr
without knowing size? possible?
class baseclass { public: baseclass(); ~baseclass(); protected: void foo() { prtinf("%s\n", arrstr); }; }; class derivedclass : public baseclass { public: derivedclass(); ~derivedclass(); protected: char arrstr[] = "foostring!"; };
add (pure) virtual access functions in base class implement in derived class.
#include <iostream> #include <string> class baseclass { protected: void foo() { std::cout << getstring() << std::endl; } private: virtual std::string getstring() const = 0; }; class derivedclass : public baseclass { private: virtual std::string getstring() const override { return "foostring!"; } };
Comments
Post a Comment