Search code examples
c++inheritancealignmentsizeofvirtual-functions

Why is the size of this subclass the same as the base class even though it adds a member variable?


In the following code, why is the size of Parent the same as the size of Child (even though Child adds a member variable)? Another weird behaviour: if I comment out the line where b is defined, the size of Child stays the same, but if I add another variable (int b, c;) then sizeof gives 24. An explanation of why this happens would be greatly appreciated (:

#include <iostream>

class Parent {
    int a = 0;
public:
    virtual void foo() {}
};

class Child : public Parent {
    int b; // this line doesn't affect the output
};

int main() {
    std::cout << sizeof(Parent) << ", " << sizeof(Child);
    return 0;
}
// Output is : 16, 16

NB : this is my first time asking questions here so feel free to ask me to edit it if it is unclear or poorly formulated.


Solution

  • Thank you all for your answers/comments, I think @Peter's answer explains it well : this is due to the 8 byte alignment required by the virtual function (on my system at least). So interestingly, without the virtual function :

    class Parent 
    {
        int a = 0;
    public:
        // virtual void foo() {}
    };
    

    The result of alignof(Parent) is 4, and so any single int variable will make a difference in the result of sizeof, but with the virtual function :

    class Parent 
    {
        int a = 0;
    public:
        virtual void foo() {}
    };
    

    alignof(Parent) now gives 8, so it would take two more int variables to change the result of sizeof.