Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the size of my class larger than the sum of its members? [duplicate]

Tags:

c++

class

sizeof

Can someone help me to understand behavior of sizeof() operator?

 #include <iostream>

using namespace std;

class A{
    int first;
    double last;
    public:
    A(int a)
    {
        cout << a << endl;
    }
};
int main()
{
    A a(3);
    cout << sizeof(a) << endl;
    return 0;
}

This code prints me size of a as 16 bytes. Size of class is calculated based on its members. So I have 4 bytes (int) + 8 bytes (double) = 12.

So why did I get 16 bytes?

When I comment out int and double members I get 1 byte.

like image 595
Paweł Jarecki Avatar asked Dec 05 '25 13:12

Paweł Jarecki


1 Answers

The layout of the fields in the class is implementation-defined, as long as POD classes are compatible with C structs. However, even in C structs implementations add padding for various reasons, like performance. Thus, your compiler is likely adding four bytes of padding after the int field in order to make the double field start at an 8-byte aligned address.

If you specifically need this to not happen, there are ways to control the alignment and padding of classes/structs, which vary among compilers. For example, GCC has syntax similar to __attribute__((packed)) that will remove that padding. This is rarely necessary - mostly when the struct will need to map to a device register - and will usually hurt performance, so avoid it if possible.

like image 102
Javier Martín Avatar answered Dec 07 '25 04:12

Javier Martín



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!