Reputation: 5110
#include<cstdio>
#include<iostream>
using namespace std;
class A
{
public:
int x;
};
class B: public A
{
};
int main()
{
B b;
b.x=5;
cout<<b.x<<endl;
return 0;
}
i have the above code.it's all okay.but i want to know when i inherit class B from class A does the member variable x declared in class B too just like A or the class B just get access to the member variable x of class A ?
are there two variables with the same name in two different classes or there are only one variable and the objects of the both classes have access to it ?
if there are two different variables with the same name in two different classes then why, when an object of derived class is declared the constructor of base class is called ?
Upvotes: 0
Views: 823
Reputation: 562
When you create an object of the derived class, a base class sub-object is embedded in the memory layout of the derived class object. So, to your question, there's only on variable that will be a part of the derived object. Since, we are only taking about non-static members here, each derived object gets its base-class sub-object laid out in memory. When you create a base class object, its a different piece of memory representing different object and has nothing to do with derived object created earlier.
Hope it clarifies your doubt!
This is a great book to understand C++ object model:
Upvotes: 1