From an answer on Inheritance: why is there a difference in behaviour between inherited and supplied variables?, I understand that the below code prints 0 because there is only one copy of x.
#include<iostream>
using namespace std;
class A {
public:
int x;
A() { x = 10; }
};
class B : public A {
public:
B() { x = 0; }
};
int main() {
A* ab = new B;
cout << ab->x << endl; // prints 0
}
But does this not go against the very meaning of inheritance?
I coded class B to interit publicly from class A, and I expected it to inherit a copy of member variable x, which should have resulted in ab->x printing value 10.
What am I missing here? I am finding it too difficult to understand why this prints 0 despite inheritance.
Here is a simple figure that briefly explains inheritance in terms of member variables:
When the
ChildClassis created, theBaseClassis created and exists inside the ChildClass. Variablesa,bandccan be accessed from bothChildClassandBaseclass(depending on access modifiers such as public, private and protected). They’re shared, not copied.