Assign pointer of derived class to pointer of base class

I assign pointer of derived class to pointer of base class.
I wonder why the address of both case are different.


Case 1

#include<iostream>
using namespace std;

class A{ public: int x; };
class B: virtual public A { /* ... */};
class C: virtual public A { /* ... */};
class D: public B, public C { /* ... */};

int main()
{
D *d1 = new D;
cout << d1 << endl;
A *a2 = d1;
cout << a2 << endl;

return 0;
}

/*
Output
0xe91770
0xe91780
*/



Case 2

#include<iostream>

using namespace std;

class A{ /* ... */ };
class B: virtual public A { /* ... */};
class C: virtual public A { /* ... */};
class D: public B, public C { /* ... */};

int main()
{
D *d1 = new D;
cout << d1 << endl;
A *a2 = d1;
cout << a2 << endl;

return 0;
}

/*
Output (class A is empty.)
0x6c1710
0x6c1710
*/


In the case where A is empty, it's address doesn't matter (it's just for identity), so it's just a copy of D's address.

In the case where A has non-static data, it's address must point to that data. If it was a copy of D's address, it would point to D's vtable instead.
Registered users can post here. Sign in or register to post.