1
    class NoVirtual {
        int a;
    public:
        void x() const {}
        int i() const { return 1; }
    };

    class OneVirtual {
        int a;
    public:
        virtual void x() const {}
        int i() const { return 1; }
    };

    class TwoVirtuals {
        int a;
    public:
        virtual void x() const {}
        virtual int i() const { return 1; }
    };

    int main() {
        cout << "int: " << sizeof(int) << endl;
        cout << "NoVirtual: "
             << sizeof(NoVirtual) << endl;
        cout << "void* : " << sizeof(void*) << endl;
  cout << "OneVirtual: "
       << sizeof(OneVirtual) << endl;
  cout << "TwoVirtuals: "
       << sizeof(TwoVirtuals) << endl;

    return 0;
}

The output is:

NoVirtual: 4
void* : 8
OneVirtual: 16
TwoVirtuals: 16

Question is:

Since OneVirtual and TwoVirtuals class have virtual function, size of class should be sizeof(int) + sizeof(void*) i.e. 12bytes. But size is printed as 16bytes.

Can someone explain why?

  • You forget about *alignment*. See [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member/119128) – Some programmer dude Dec 25 '17 at 12:03
  • You are aware of the added pointer, so [this should enlighten you](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) somewhat. It's not a direct answer however, by any means. – StoryTeller - Unslander Monica Dec 25 '17 at 12:03

1 Answers1

3

I assume you are compiling on 64bit machines since size of int is 4bytes.Typically for 64bit machines pointer size will be 8 bytes and int size is 4 bytes.To satisfy Data Alignment requirement to save read cycles compiler adds extra 4 bytes(padding) hence result is 16bytes where as actual required size is 12 bytes.

Vin
  • 48
  • 6