virtual base class problem

Started by
3 comments, last by SiCrane 18 years, 1 month ago

#include<iostream>
using namespace std;
class a
{
int x;
};

class b:virtual public a
{
int y;
};



class c:virtual public a
{
int z;
};

class d:public b,public c
{
};

int main()
{

cout<<sizeof(d);
}
In this sizeof class d come out to be 20 bytes...Is it because of extra 4 bytes for virtual pointer??
Advertisement
Under most 32 bit compilers it would have 12 bytes for x, y and z, 4 bytes for the class b vptr and 4 bytes for the class c vptr.
Quote:Original post by SiCrane
Under most 32 bit compilers it would have 12 bytes for x, y and z, 4 bytes for the class b vptr and 4 bytes for the class c vptr.


Does every class have their own virtual table and virtual pointer or there is only single virtual table but different virtual pointers for different classes??
Most of the time, there is one v-table per class, and every instance of that class has a pointer to that v-table. Technically the implementation details are not guaranteed, but in practice that's often how its done.
Thats not true for multiple inheritance. Most compilers will create a vtable for each vtable that each direct base class has, less the number of excess virtual base class vtables. In this case, d will probably have two vtables.

This topic is closed to new replies.

Advertisement