Why doesnt the subclasses share the same private membervariable in the superclass using polymoprhism? There are only one instance of the baseclass and if SubA is setting the private member through a mutator - why then cannot SubB access this value. How would it look like if I want the subclasses to share the 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
That is wrong.
aandbare different objects. They each have an instance of anAsub object. You have not setcntinb, so it is no surprise that looking at it gives you a garbage value, because reading from an uninitialized object is undefined behaviour.You could give the base class a
staticdata member. That means all instances ofAwould share the same member.