c++ - Virtual inheritance using empty classes -


can tell exact reason output of following code in c++ ?the output received code included in header comments. have virtual table , v pointer.

/* sizeof(empty) 1                                                                                  sizeof(derived1) 1   sizeof(derived2) 8   sizeof(derived3) 1   sizeof(derived4) 16   sizeof(dummy) 1 */  #include <iostream> using namespace std;  class empty {};  class derived1 : public empty {};  class derived2 : virtual public empty {};  class derived3 : public empty {     char c; };  class derived4 : virtual public empty { char c; };  class dummy {  char c; };  int main() {      cout << "sizeof(empty) " << sizeof(empty) << endl;     cout << "sizeof(derived1) " << sizeof(derived1) << endl;     cout << "sizeof(derived2) " << sizeof(derived2) << endl;     cout << "sizeof(derived3) " << sizeof(derived3) << endl;     cout << "sizeof(derived4) " << sizeof(derived4) << endl;         cout << "sizeof(dummy) " << sizeof(dummy) << endl;     return 0;  } 

firstly, class no members must have non-zero size. standard insists on that. otherwise pointer arithmetic , arrays not work array of zero-sized class have elements in same place!

the fact other sizes differ may due v-table. not mandated explicitly in standard, manifestation of way compiler dealing things.

note polymorphism requires @ least 1 virtual method defined in base class. accounts sizeof(derived1) being same size base class.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -