"Patricia" <la******@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
First, I know the following code is bad, but it's from a library I have
to use, and I can't change it.
class A {
// some primitive members
};
class B {
// some primitive members
};
class C : public A, B {
// no members
};
main() {
// I know sizeof(A) = 16, sizeof(B) = 60
C * pc = (C*) new char[sizeof(A) + sizeof(B)];
B * pb = (B*) pc;
char * p1 = (char *) pc;
char * p2 = (char *) pb;
cout << "offset : " << (p2 - p1) << endl;
}
What surprised me is that the offset is 20 instead of 16. Do you know
the possible reason?
The following is a better way of doing what you are trying to do:
#include <iostream>
#include <memory>
class A {
// some primitive members
int a[4];
};
class B {
// some primitive members
int a[15];
};
class C : public A, public B {
// no members
};
int main() {
std::cout << " sizeof(A): " << sizeof(A)
<< " sizeof(B): " << sizeof(B)
<< " sizeof(C): " << sizeof(C)
<< '\n';
// Allocate a buffer
char * buffer = new char[sizeof(C)];
// Use placement new to construct an object on that buffer
C * pc = new (reinterpret_cast<void *>(buffer)) C();
// A valid up-cast
B * pb = pc;
char * p1 = reinterpret_cast<char *>(pc);
char * p2 = reinterpret_cast<char *>(pb);
// WARNING: Undefined behavior below! We cannot subtract two
// pointers unless they point to objects of the same
// array. Nevertheless, the results may be useful on a given system.
std::cout << "offset : " << (p2 - p1) << endl;
// Destroy the C object manually and release the buffer
pc->~C();
delete buffer;
}
Ali