How can this be?

B

bergmush

#include <iostream>

using namespace std;

class A {
};

class B {
};

class C : public A, public B {
};

int main() {

A *pA = 0;
B *pB = 0;
C c;

pA = &c;
pB = &c;


cout << sizeof(c) << endl;
cout << pA << " : " << pB << " : " << &c << endl;

return 0;
}

OUTPUT:
1
0012FF74 : 0012FF75 : 0012FF74

Why does sizeof return 1 but when looking at the pointers we get
addresses of two different bytes in memory?
 
G

Gianni Mariani

Why does sizeof return 1 but when looking at the pointers we get
addresses of two different bytes in memory?

This is an implementation detail.

Anyhow, I don't recall the C++ standard here, but it does talk about
having distinct addresses for different objects. In this case, pA and
pB might need to be distinct, I'm not sure though.
 
A

Alf P. Steinbach

* (e-mail address removed):
#include <iostream>

using namespace std;

class A {
};

class B {
};

class C : public A, public B {
};

int main() {

A *pA = 0;
B *pB = 0;
C c;

pA = &c;
pB = &c;


cout << sizeof(c) << endl;
cout << pA << " : " << pB << " : " << &c << endl;

return 0;
}

OUTPUT:
1
0012FF74 : 0012FF75 : 0012FF74

Why does sizeof return 1 but when looking at the pointers we get
addresses of two different bytes in memory?

At first sight I thought that must be wrong. But. Since classes A and
B are empty the compiler is free to apply the empty base class
optimization, reducing the size of each base class sub-object to zero.
It then has to represent a pointer to a base class object in some way,
and since there are two base classes, two different pointer values are
needed. All that's required is that if you cast back down you will
consistently get &c, and surely you do?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top