Re: Multiple inheritance
junw2000@gmail.com wrote:
Below is a simple code about multiple inheritance
#include <iostream>
class A{
int x;
};
class B{
int y;
};
class C : public A, public B{
int z;
};
int main(){
A * a;
B* b;
C c;
a = &c;
b = &c;
std::cout<<"a:"<<a<<" b:"<<b<<" &c:"<<&c<<std::endl;
}
The output is:
a:0xbffff540 b:0xbffff544 &c:0xbffff540
Why a and b are different?
You should try to layout what the classes look like in memory to see it
more clearly:
here's a simplified view:
A -> [int - x]
B -> [int - y]
C -> [int - x | int - y | int - z]
As you can see, C contains the members of both A and B, so a pointer to
a C object would point to the beginning of all the data, i.e. "x".
If I create a pointer of type A and have it point to an object of type
C, since the A object contains "x", it will also point to that
location, the same as the C object.
If I create a pointer of type B and have it point to an object of type
C, since the B object only contains "y", it will need to point to the
"y" location in the C object, so that it correctly looks like a B
object.
In your example, you see that the B pointer is 4 bytes greater than the
A pointer (the size of an int on a 32 bit platform) which fits
perfectly with my example above.