Newbie's asks on inheritance

How actually in real run time a derived class is implementing inheritance as class is just abstract
1
2
3
4
5
class A { 
public :
  int a;
};
class B : public A { int b; };


Does a B object instantly "realize" that it's containing an A object ?
1
2
3
4
5
6
7
int main () {
 A aA;
 B aB;        // How is inheritance's real implementation

 aB.a = 3;    //   ?

}

Last edited on
Your code will fail to compile because the "a" data member and the "b" data member are private by default. To fix this, you can either make both of them "structs" or you can change their access specifiers.

In any case, to answer your question, in memory, a "B" object looks like an "A" object, at least at the beginning. The B object appends its data members in memory after its base classes, which is A. This means it looks like this:
1
2
3
4
5
6
7
A object in memory:
[int a]

B object in memory:
[int a]
[int b]


Since you derived B from A, all objects of B are, in fact, also objects of A. That is to say, all B objects will always have "A" data members contained within it. Thus, when you have a B* that points to a B object, it actually points somewhere in the middle of the object, where the B sub-object data members begin.
Note: Was Edited due to above urge
Did you understand?
Topic archived. No new replies allowed.