Why object with vptr is 12 bytes longer?

177 views Asked by At
#include <iostream>

class B
{
    public:
    virtual void f() {std::cout<<"HI";}
    int x;
};
class A
{
    public:
    void f() {std::cout<<"HI";}
    int x;
};

int main () {
  A a;
  B b;
  std::cout<<sizeof(a)<<" "<<sizeof(b);

  return 0;
}

The output is

4 16 

I expected it to be 8 bytes longer - vptr pointer. But for what the rest 4 bytes is used? I found quite many forum posts (all from some years ago) where people discussed that object from the class with vprt is 4 or 8 bytes longer. I checked also on online C++ shell - output there is the same.

1

There are 1 answers

0
Vlad from Moscow On

It seems that the pointer to the table of pointers to virtual functions has a size of 8 bytes. So the class B is aligned to the boundary of 8 bytes that is it has 4 additional padding bytes.