Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Inheritance: Different Address same address

Tags:

c++

I have written a sample program. If I print the address of pa and pb both are different. Can you let me know why is this happening ?

#include<iostream>
using namespace std;
class A {
int x;
};

class B {
int y;
};

class C: public A, public B {
int z;
};

int main()
{
 C c;
 A *pa;
 B *pb;

 pa = &c;
 pb = &c;

cout<<pa<<endl;
cout<<pb<<endl;

}
like image 871
Varun Avatar asked Mar 16 '23 13:03

Varun


1 Answers

As Kerrek SB put it, pa and pb in your example don't actually point to c, but rather to the A and B subobjects of c.

With multiple inheritance, the data from the base classes is essentially stacked one after another. Base-typed pointers are simply offset to the data for that base class. Because of this, pa and pb point at different offsets into c.

#include<iostream>
using namespace std;

class A {
    public:
    int x;
};

class B {
    public:
    int y;
};

class C: public A, public B {
    public:
    int z;
};

int main()
{
    C c;
    cout << "    &c: " << &c << endl << endl;

    cout << "(A*)&c: " << (A*)&c << endl;
    cout << "(B*)&c: " << (B*)&c << endl << endl;

    cout << "  &c.x: " << &c.x << endl;
    cout << "  &c.y: " << &c.y << endl;
    cout << "  &c.z: " << &c.z << endl << endl;
}

Result:

    &c: 0x7ffdfeb26b20

(A*)&c: 0x7ffdfeb26b20
(B*)&c: 0x7ffdfeb26b24

  &c.x: 0x7ffdfeb26b20
  &c.y: 0x7ffdfeb26b24
  &c.z: 0x7ffdfeb26b28

So you can see that C is laid out like this:

                  ---------------
0x7ffdfeb26b20    |     x       |     class A data
                  ---------------
0x7ffdfeb26b24    |     y       |     class B data
                  ---------------
0x7ffdfeb26b28    |     z       |     class C data
                  ---------------

If you add some virtual methods to this example, you'll see that the same things happens with the subclass vtables.

like image 157
Jonathon Reinhart Avatar answered Mar 23 '23 02:03

Jonathon Reinhart