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).
#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).
Parvath can you explain little more on these:
ReplyDelete1) 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 ?