int is 4 bytes, char is 1 byte. Why, then, at the very bottom of the program, 12 is displayed instead of 9?

class A { public: A() {} ~A() {} void f_a(); private: int var_a; }; class B : public A { public: B() {} ~B() {} void f_b(); private: int var_b; }; class C : public B { public: C() {} ~C() {} void f_c(); private: char var_c; }; int main() { A objA; B objB; C objC; cout << sizeof(objA) << endl; // выводит 4 cout << sizeof(objB) << endl; // выводит 8 cout << sizeof(objC) << endl; // выводит 12??? почему ни 9? return 0; } 

    1 answer 1

    In order to create arrays of objects, and at the same time so that each object in the array is aligned according to the corresponding value, the memory occupied by the objects can be added so that the object next to this object is located at the correct aligned address.

    This allows you to correctly use pointer arithmetic, since increasing the pointer by one increases its value by sizeof( тип объекта ) .

    In your case, objects of class C aligned with the border corresponding to the type of int , and therefore 3 bytes are added to the end of the object to get a multiple of sizeof( int ) ..

    If your compiler supports the alignof keyword, then you can get the value by which the memory address for objects of your classes is aligned. So sentence

     std::cout << alignof( C ) << std::endl; 

    displays the value on the console

     4 

    which corresponds to the value of sizeof( int ) . That is, an object of class C placed on the border of integers. To ensure this, each object is padded with 3 bytes.

    • In general, yes, but what is the reason for the arrays? - Qwertiy
    • And all. I reread the code. Something I did not understand the question at first. - Qwertiy
    • @Qwertiy Because correctly positioning one object is not a problem. - Vlad from Moscow
    • If for class B the variable type is changed to double , then the output will be results 4, 16, 24. That is, first an array of type int for an object of class A, and then the compiler will see that the next class contains a variable of type double , after which it will create an array of objects of type `double`, will copy the value of an object of class A, then move the object of class B and enclose the class C? Did you understand everything correctly? - Dima Kozyr
    • one
      @dmitrykozyr No arrays are created. In class A, a class member with type int must be aligned to the boundary for type int. Since class B has an object of type double, it must be aligned with the boundary for double types. Since a double usually takes 8 bytes, class B objects are aligned to this value. - Vlad from Moscow