Sign in to follow this  

virtual base class problem

This topic is 4309 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

#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??

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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??

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4309 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this