GitHub
Blog
Previous

C++ Padding: How Reordering Just One Line Changed My Class Size

C++ Padding: How Reordering Just One Line Changed My Class Size

While revising OOP for an internship interview, a simple class printed 24 bytes instead of 13 — and reordering a single member dropped it to 16. Here's what memory alignment and padding taught me.

A few hours ago, I was revising OOP for my internship interview, when I stumbled upon something that completely caught me off guard.

I had a very simple class:

class Test {
    char c;     // 1 byte
    double x;   // 8 bytes
    int marks;  // 4 bytes
};

Now, in my head, I quickly did the math:

1 (char) + 8 (double) + 4 (int) = 13 bytes.

So naturally, I thought:

std::cout << sizeof(Test) << std::endl;

would print 13.

But nope.

It printed 24.

Wait… what?

I stared at the output for a good few seconds. How can a class with just 13 bytes worth of variables take up 24 bytes in memory?

That was my first encounter with something called padding in C++.

My Curiosity Got the Better of Me

I rewrote the class, this time just shuffling the order of members:

class Test {
    double x;   // 8 bytes
    char c;     // 1 byte
    int marks;  // 4 bytes
};

This time, I thought, "Okay, maybe now it will finally be 13 bytes."

But when I printed it again:

std::cout << sizeof(Test) << std::endl;

I got 16.

Not 13. Not 24. But 16.

So What's Happening Here?

That's when I realized — the compiler isn't just storing my variables back-to-back. It's also making sure each variable is aligned properly in memory so the CPU can access them efficiently.

  • A double wants to sit at an address divisible by 8.
  • An int likes being on an address divisible by 4.
  • A char doesn't really care much.

When the order is char → double → int, the compiler has to insert extra invisible padding bytes to keep everything aligned. That's why the class bloats up to 24 bytes.

Rule: Struct/Class Size Must Be a Multiple of the Largest Member's Alignment

Every struct or class has an alignment requirement equal to the largest alignment of its members.

In this example:

  • char = 1
  • double = 8
  • int = 4
  • Largest = 8

So the compiler ensures the total size of the struct/class is a multiple of 8.

But when the order is double → char → int, the compiler needs fewer padding bytes, and the total size drops to 16 bytes.

It suddenly clicked for me: the way you order your class members in C++ actually changes how much memory your class takes up.

  • Bad ordering (wasted memory): 24 bytes
  • Good ordering (optimized): 16 bytes

And both have the same variables!