#include #include #include using namespace std; class grandparent { int i; public: grandparent(int initial_i): i(initial_i) {} int f() const {return i;} }; class mother: public virtual grandparent { int j; public: mother(int initial_i, int initial_j) : grandparent(initial_i), j(initial_j) {} struct table { ptrdiff_t diff; //offset from end of mother to its grandparent }; struct layout { const table *p; int j; }; }; struct father: public virtual grandparent { int k; father(int initial_i, int initial_k) : grandparent(initial_i), k(initial_k) {} }; struct stepfather: public virtual grandparent { int k2; stepfather(int initial_i, int initial_k2) : grandparent(initial_i), k2(initial_k2) {} }; struct grandchild: public mother, public father { int l; grandchild(int initial_i, int initial_j, int initial_k, int initial_l) : grandparent(initial_i), mother(initial_i, initial_j), father(initial_i, initial_k), l(initial_l) {} }; struct stepgrandchild: public mother, public father, public stepfather { int l; stepgrandchild(int initial_i, int initial_j, int initial_k, int initial_k2, int initial_l) : grandparent(initial_i), mother(initial_i, initial_j), father(initial_i, initial_k), stepfather(initial_i, initial_k2), l(initial_l) {} }; void print(const mother *m); int main() { cout << "sizeof mother, not counting its grandparent, is " << sizeof (mother) - sizeof(grandparent) << ".\n\n"; grandchild g(10, 20, 30, 40); cout << "mother in grandchild:\n"; print(&g); stepgrandchild sg(50, 60, 70, 80, 90); cout << "mother in stepgrandchild:\n"; print(&sg); return EXIT_SUCCESS; } void print(const mother *p) { const mother::layout& lay = reinterpret_cast(*p); const ptrdiff_t diff = lay.p->diff; const char *const cp = reinterpret_cast(p) + sizeof (mother) - sizeof (grandparent); const grandparent *const gp = reinterpret_cast(cp + diff); cout << p << " == address of mother\n" << static_cast(cp) << " == address of first byte after mother" " (not counting its grandparent)\n" << hex << setw(10) << diff << dec << " == offset to mother's grandparent (in hex)\n" << gp << " == address of mother's grandparent\n" << static_cast(p) << " == static_cast(p)\n" << "grandparent's f returns " << gp->f() << ".\n\n"; }