//: C09:Offset.cpp // Illustrates layout of subobjects with MI. #include <iostream> using namespace std; class A { int x; }; class B { int y; }; class C : public A, public B { int z; }; int main() { cout << "sizeof(A) == " << sizeof(A) << endl; cout << "sizeof(B) == " << sizeof(B) << endl; cout << "sizeof(C) == " << sizeof(C) << endl; C c; cout << "&c == " << &c << endl; A* ap = &c; B* bp = &c; cout << "ap == " << static_cast<void*>(ap) << endl; cout << "bp == " << static_cast<void*>(bp) << endl; C* cp = static_cast<C*>(bp); cout << "cp == " << static_cast<void*>(cp) << endl; cout << "bp == cp? " << boolalpha << (bp == cp) << endl; cp = 0; bp = cp; cout << bp << endl; } /* Output: sizeof(A) == 4 sizeof(B) == 4 sizeof(C) == 12 &c == 1245052 ap == 1245052 bp == 1245056 cp == 1245052 bp == cp? true 0 */ ///:~
Listado 8.10. C09/Offset.cpp
//: C09:Duplicate.cpp // Shows duplicate subobjects. #include <iostream> using namespace std; class Top { int x; public: Top(int n) { x = n; } }; class Left : public Top { int y; public: Left(int m, int n) : Top(m) { y = n; } }; class Right : public Top { int z; public: Right(int m, int n) : Top(m) { z = n; } }; class Bottom : public Left, public Right { int w; public: Bottom(int i, int j, int k, int m) : Left(i, k), Right(j, k) { w = m; } }; int main() { Bottom b(1, 2, 3, 4); cout << sizeof b << endl; // 20 } ///:~
Listado 8.11. C09/Duplicate.cpp