XoMute
XoMute

Reputation: 51

Different sizeof() of struct and class with the same field types in each other

I already know, that in structure there are paddings between fields, and size of whole structure depends on their order or something like that. But does it work the same way for classes?

I have some struct like:

typedef struct {
    char *b;
    int s;
} class_t;

And I also have a class with the same fields:

class Class{
private:
    char *m_buf;
    int m_size;
};

The question is: why sizeof(class_t) gives 16 bytes, and sizeof(Class) gives 12 bytes?

Upvotes: 0

Views: 1202

Answers (2)

user4442671
user4442671

Reputation:

The 12 number is suspicious. It's a bit of a weird size, and tells me the compiler is doing something funky with the layout.

Since you mentionned GCC, I would imagine that struct packing has been enabled on that class, either through __attribute__((packed)) (most likely in a macro), or via the pack() pragma somehow.

You can see this behavior in action here: https://gcc.godbolt.org/z/XEkH7f

Upvotes: 2

Jesper Juhl
Jesper Juhl

Reputation: 31467

Except for the fact that a struct and a class have different default access specifications and different default inheritance (public vs private), a class and a struct are exactly the same.

Upvotes: 2

Related Questions