Multiple Inheritance: Different Address Addresses

I wrote an example program. If I print the address pa and pb, then they are different. Can you tell me why this is 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;

}
+4
source share
3 answers

As Kerrek SB put it, paand pbin your example does not really point to c, and the sooner on Aand Bsub-objects c.

With multiple inheritance, the data of the base classes are essentially stacked one after another. Pointers with a base type are simply shifted to the data for this base class. Because of this, pathey pbindicate different displacements on 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 as follows:

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

, , vtables.

+7
    ---------   <------pa = &c
   |    x    |
    ---------   <------pb = &c
   |    y    |
    ---------
   |    z    |
    ---------

, - C

0

, .

struct Base{
   int baseMember;
}

struct Child{
   struct Base parent;
   int someMoreMembers;
}

, Child, , Base, . ++ (). , . , ++ , , .

0
source

All Articles