Search code examples
c++virtualsizeofbase-class

Size of an array inherited virtually from two classes


Consider the following program:

#include<iostream>
using namespace std;
  
class base {
  int arr[10];     
};
  
class b1: virtual public base { };
  
class b2: virtual public base { };
  
class derived: public b1, public b2 {};
  
int main(void)
{ 
  cout<<sizeof(derived);
   return 0;
}

According to me, the array arr is inherited only once in the class due to virtual base class. Hence sizeof derived class should be 10*4=40 bytes. However, on execution, this program is printing 56 as the output. I even checked the size of int on the compiler, it was 4 bytes only. Can someone explain me where are the additional 16 bytes coming from?


Solution

  • It is probably size of v-table for keeping virtual function addresses. If you check b1 or b2, it is 48 bytes, probably a pointer to v-table(pointer on 64 bit system is 8 bytes). same thing happens for next inheritance increasing size by 8 more.

    Side note: I think it is v-table because if you compile your code as a 32-bit program, the increase of sizes will be 4 bytes(pointer in 32 bit system). In addition, if you remove virtual keyword the size will not increase anymore, so it is obviously something related to virtual calls and first thing that comes to mind is v-table.