-1

I don't undertand the output shown below.

I know that whenever a virtual function is present it creates a vptr but still the size printed is more than I would expect:

#include<iostream>
using namespace std; 

class Base
{
 int x;
 int y;
 int z;
public:
 virtual void fun(){}
 virtual void fun2(){}
};

class Derived:public Base
{
 public:
  void fun() override {} 
};

int main(int argc, char const *argv[])
{
  cout<<sizeof(Base)<<endl;
  cout<<sizeof(Derived)<<endl;
  cout<<sizeof(int)<<endl; 
}

24
24
4
[Finished in 0.3s]

hauron
  • 4,550
  • 5
  • 35
  • 52
Pritul Dave
  • 189
  • 1
  • 11

1 Answers1

6

Is this a 64 bit build? If so, sizeof Base would be:

8 (vtable pointer) + (3 * 4 = 12) (member variables) + 4 (pad to multiple of 8 bytes) = 24

Since Derived derives only from Base and adds no member variables, its size is the same.

Why is padding added? To maintain 8-byte alignment in arrays and on the stack. Why is that important? That's a different question.

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48