Pergunta

I am new to C++ programming, in the below code i am using virtual inheritance so size of derived class is showing 24 bytes but i am not getting how it is so please help me how exactly it is.

#include "stdafx.h"
#include <iostream>
using namespace std;

class BaseClass
{
      private : int a, b;
      public :
  BaseClass()
  {
    a = 10;
    b = 20;
  }
  virtual int area()
  {
    return 0;
  }
};

class DerivedClass1 : virtual public BaseClass
{
  int x;
      public:
  virtual void simple()
  {
    cout << "inside simple" << endl;
  }
};

int main()
{
   DerivedClass1 Obj;
   cout << sizeof(Obj) << endl;
   return 0;
}
Foi útil?

Solução

I guess that you're compiling as 64-bit? In that case, your DerivedClass1 will probably be laid out in memory with this arrangement of bytes:

offset     size    type
0          8       pointer to virtual function table
8          4       int BaseClass::a
12         4       int BaseClass::b
16         4       int DerivedClass1::x
20         4       filler, so that the total size of this class is an even number of 64-bit (8-byte) words

The pointer to virtual function table is silently added to your class by the C++ compiler for any class that is part of a class inheritance hierarchy containing any virtual functions.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top