Sunday, 6 April 2014

Size of virtual class in c++

What is the size of a class, if it is part of virtual inheritance?


#include<iostream>
using namespace std;

class base {
public:
  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)<<"    "<<sizeof(int)<<endl;;
  getchar();
  return 0;
}

Output : 48
If you do non-virtual inheritance then it is 80(two copies from b1 & b2)

But if we do virtual inheritence then we are getting 8 additional bytes, where are we are supposed to get 40(single copy).So from where these additional bytes are comming.?

Reason: Since the methods are virtual, compiler add 4 bytes from each b1,b2 for vptr(virtual pointer).

1 comment:

  1. Parvath can you explain little more on these:
    1) Referring to "Single copy" in your statement, which base class copy will it inherit?
    2) Why do we have two vptr when only one copy is inherited ?

    ReplyDelete

AWS Data Pipeline Services

https://www.youtube.com/watch?v=tykcCf-Zz1M