C ++ Object Memory layout -- compiler GCC compiler -- virtual inheritance -- diamond inheritance
// GCC compiler -- virtual inheritance -- diamond inheritance. CPP // 2010.8.19 // GCC compiler # include <iostream> using namespace STD; //////////////////////////////////////// /// // class base {public: base (int A = 10): A (a) {} virtual void show () {cout <"base: Show () "<" \ t "<A <Endl;} virtual void TESTA () {cout <" base: TESTA () "<" \ t "<A <Endl;} PRIVATE: int ;}; //////////////////////////////////////// //////////// /// // Class basea: virtual public base {public: basea (int B = 20): B (B) {} virtual void Showa () {cout <"basea: Showa ()" <"\ t" <B <Endl;} void TESTA () {cout <"basea :: testa () "<" \ t "<B <Endl;} PRIVATE: int B ;}; //////////////////////////////////////// /// // class baseb: virtual public base {public: baseb (INT c = 30): C (c) {} virtual void showb () {cout <"Baseb: showb ()" <"\ t" <C <Endl;} PRIVATE: int C ;}; //////////////////////////////////////// /// // class derived: public basea, public baseb {public: derived (INT d = 40): D (d) {}virtual void show () {cout <"derived: Show () "<" \ t "<D <Endl;} virtual void test () {cout <" derived: Test () "<" \ t "<D <Endl;} PRIVATE: int D ;}; //////////////////////////////////// /// // Int main () {derived OBJ; int ** P = (INT **) & OBJ; cout <"derived OBJ memory layout:" <Endl; For (INT I = 0; I! = Sizeof (OBJ)/4; ++ I) {cout <p [I] <Endl ;}cout <Endl; typedef void (* Fun) (void * pthis); // very important/* call a function through the virtual function table * // * the first virtual function table pointer. Basea */(fun) (p [0] [0]) (p); (fun) (p [0] [1]) (p ); // The first two are basea (fun) (p [0] [2]) (p); (fun) (p [0] [3]) (p); // the last two are derived's/* The second virtual function table pointer. Baseb */cout <Endl; (fun) (p [2] [0]) (p + 2);/* pointer of the third virtual function table. Base */cout <Endl; (fun) (p [5] [0]) (p + 5); (fun) (P [5] [1]) (p + 5); Return 0;}/* derived OBJ memory layout: direction: Showa () 20 basea: TESTA () 20 derived: Show () 40 derived: Test () 40 baseb: showb () 30 derived: Show () 40 basea: TESTA () 20 */