C ++ Object Memory Layout-compiler vs compiler-virtual inheritance-diamond inheritance
// Vs compiler -- virtual inheritance -- diamond inheritance. CPP // 2010.8.19 // vs 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 <"ba Seb: 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 sizeof =" <sizeof (OBJ) <Endl; cout <"derived OBJ memory layout:" <Endl; For (INT I = 0; I! = Sizeof (OBJ)/4; ++ I) {cout <p [I] <Endl;} cout <Endl; typedef void (_ thiscall * Fun) (void * pthis); // very important/* call the first virtual function table pointer of a function through the virtual function table. Basea */(fun) (p [0] [0]) (p); (fun) (p [0] [1]) (p ); // The second virtual function table pointer. Basebcout <Endl; (fun) (p [3] [0]) (p + 3); // The third virtual function table pointer. Base cout <Endl; (fun) (p [8] [0]) (p + 8); (fun) (p [8] [1]) (p + 8); System ("pause"); Return 0;}/* derived OBJ sizeof = 40 derived OBJ memory layout: direction: Showa () 20 derived :: test () 40 baseb: showb () 30 derived: Show () 40 basea: TESTA () 20 */