Start New Discussion within our Software Development Community

I have a base class and two derived class. One derived class which inherits base class as virtual and another one as non virtual. I have given below my codin.

// This program uses virtual base classes.
    #include <iostream>
    using namespace std;
    class base {
    int i;
    // derived inherits base as not virtual
    class derived : public base {
    int x;
    // derived1 inherits base as virtual.
    class derived1 : virtual public base {
    int j;
    int main()
    base b;
    cout<<endl<<sizeof(b)<<" ";
    derived obn;
    cout<<sizeof(obn)<<" ";
    derived1 ob1;
    return 0;

After running this program i get the below output

12 > "Why the virtual derived class having 12 bytes? "

Given the size difference, I'd say that your compiler implements virtual bases using a virtual base pointer (much like the better known virtual table pointer for polymorphism). Extra bookkeeping is required to maintain the shared instance, because the compiler can't simply stack the instances as in non-virtual inheritance.

This article has been dead for over six months. Start a new discussion instead.