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
Polymorphism has nothing to do with how data is embedded in classes; (run-time) polymorphism is only relevant to
virtual
dispatch and Run-Time Type Information (RTTI) fordynamic_cast
andtype_info
.If you imagine your
a
andb
objects on the stack, their memory layout can be illustrated like this:In effect,
class A : public Super
is saying "I may want to extend 'Super', optionally appending my own data members to those inSuper
, possibly adding further functions / overridingvirtual
ones".This is wrong... each sub class embeds its own instance of the super class.
Well, there are lots of ways in which you could orchestrate that:
You could have the subclasses hold pointers to a
Data
object into which you move the superclass's data you want shared, then you'd need a way to initialise theData
object and make it known to all the subclass instances you want to share it.You could make the superclass data
static
, which means a single copy of eachstatic
variable will be shared by all instances of the superclass, whether embedded in subclasses or not.