c++ - Polymoprhism - subclasses sharing of baseclass private members -


why doesnt subclasses share same private membervariable in superclass using polymoprhism? there 1 instance of baseclass , if suba setting private member through mutator - why cannot subb access value. how if want subclasses share same private member?

 #include <iostream> class super {     private:      int cnt;    public:      int getcnt() {         return cnt;      }      void setcnt(int cnt) {         this->cnt = cnt;      } };  class suba: public super {  };  class subb: public super {  };  int main() {    super *super;   suba a;   subb b;    super = &a;   super->setcnt(10);   super = &b;   std::cout << super->getcnt() << std::endl;   super = &a;   std::cout << super->getcnt() << std::endl;   return 0; } 

produces:

-8589546555 (garbage) 10 

there 1 instance of baseclass , if suba

that wrong. a , b different objects. each have instance of a sub object. have not set cnt in b, no surprise looking @ gives garbage value, because reading uninitialized object undefined behaviour.

how if want subclasses share same private member?

you give base class static data member. means instances of a share same member.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -