Skip to main content
Be Bitwise
C++What Your C++ Code Actually Does

Objects in Memory

C++ classes look like a fancy abstraction sitting on top of C structs. Constructors, destructors, member functions, access specifiers, inheritance, the works. Drop down to the machine level and most of that scaffolding evaporates. In this lesson we'll trace exactly how the compiler lays classes out in memory, and what's left of object orientation once it's compiled.

A Simple Class

cpp
class Point {
public:
int x;
int y;
Point(int x, int y) : x(x), y(y) {}
int sum() const { return x + y; }
};
int main() {
Point p(3, 4);
int s = p.sum();
return s;
}

Compiled with g++ -S -masm=intel -O0:

asm
; Point::Point(int, int) - the constructor
; 'this' pointer is the hidden first argument in rdi
_ZN5PointC1Eii:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi ; Store 'this'
mov DWORD PTR [rbp-12], esi ; Store x parameter
mov DWORD PTR [rbp-16], edx ; Store y parameter
mov rax, QWORD PTR [rbp-8] ; Load 'this'
mov edx, DWORD PTR [rbp-12] ; Load x
mov DWORD PTR [rax], edx ; this->x = x (offset 0)
mov rax, QWORD PTR [rbp-8] ; Load 'this' again
mov edx, DWORD PTR [rbp-16] ; Load y
mov DWORD PTR [rax+4], edx ; this->y = y (offset 4)
nop
pop rbp
ret
; Point::sum() const
; 'this' pointer in rdi
_ZNK5Point3sumEv:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi ; Store 'this'
mov rax, QWORD PTR [rbp-8] ; Load 'this'
mov edx, DWORD PTR [rax] ; edx = this->x (offset 0)
mov rax, QWORD PTR [rbp-8] ; Load 'this' again
mov eax, DWORD PTR [rax+4] ; eax = this->y (offset 4)
add eax, edx ; eax = x + y
pop rbp
ret

Three things worth pulling out:

  1. this is a hidden first argument. The constructor Point(int x, int y) actually has THREE parameters at the assembly level: rdi holds this, rsi holds x, edx holds y. Every non-static member function gets this shoved in front.

  2. Member access is just struct offsets. this->x is [rax+0], this->y is [rax+4]. Same instructions you'd see for plain old C struct field access.

  3. The class has the same layout as a C struct. A Point object is 8 bytes flat. Two 4-byte ints, no padding, no metadata, no overhead.

Name Mangling

Notice the gnarly function names: _ZN5PointC1Eii and _ZNK5Point3sumEv. That's name mangling. The compiler smushes the class name, function name, parameter types, and const-ness all into a single linker symbol. Run it back through c++filt to decode:

bash
c++filt _ZN5PointC1Eii
# Output: Point::Point(int, int)
c++filt _ZNK5Point3sumEv
# Output: Point::sum() const

That mangling is what makes function overloading work. Two functions with the same name but different parameter lists end up with different mangled symbols, so the linker, which insists every symbol be unique, stays happy.

Classes with Virtual Functions

Once a class picks up virtual functions, the layout shifts:

cpp
class Animal {
public:
int weight;
virtual void speak() { }
virtual ~Animal() { }
};
class Dog : public Animal {
public:
int breed_id;
void speak() override { }
};

The memory layout of a Dog object:

That vtable pointer is an 8-byte pointer pinned at offset 0. It points at a table of function pointers keyed to the object's actual runtime type. The next lesson dissects vtables in detail.

You might expect 24 bytes here. A standalone Animal is 16 bytes (vptr, weight, then 4 bytes of tail padding to keep the size a multiple of 8). But the x86-64 Itanium C++ ABI that GCC and Clang follow lets a derived class put its own members into the tail padding of a non-POD base, and Animal stops being POD the moment it has a virtual function. So breed_id slots in at offset 12 and sizeof(Dog) is 16. Check it with sizeof(Dog) and offsetof-style pointer arithmetic on &d.breed_id; you'll get 16 and 12.

The Cost of Virtual

A single virtual keyword fattens every instance of the class by 8 bytes for the vtable pointer, plus whatever padding that pointer's 8-byte alignment drags in. Multiply that across millions of objects and you're paying real money for a feature you might not be using. If you don't need polymorphism, don't reach for virtual.

Constructor and Destructor Calls

Behind the scenes, the compiler is inserting constructor calls when you create an object and destructor calls the moment it leaves scope:

cpp
class Resource {
public:
int *data;
Resource() { data = new int(42); }
~Resource() { delete data; }
};
void example() {
Resource r; // Constructor called here
// ... use r ...
} // Destructor called here automatically
asm
example:
push rbp
mov rbp, rsp
sub rsp, 16
; Construct r: call Resource::Resource()
lea rdi, [rbp-16] ; 'this' = address of r on stack
call _ZN8ResourceC1Ev ; Resource::Resource()
; ... use r ...
; Destruct r: call Resource::~Resource()
lea rdi, [rbp-16] ; 'this' = address of r
call _ZN8ResourceD1Ev ; Resource::~Resource()
leave
ret

That destructor call at the bottom of example? The compiler put it there. You never typed it. That's RAII in action: the compiler is on the hook for running the destructor when the object exits its scope.

Inheritance Layout

Single inheritance is the friendly case. The derived class glues its fields onto the end of the base's:

cpp
class Base {
public:
int a; // offset 0
int b; // offset 4
};
class Derived : public Base {
public:
int c; // offset 8
int d; // offset 12
};

The layout is simply:

text
[Base fields] [Derived fields]
[a (4)] [b (4)] [c (4)] [d (4)]

A Derived* can stand in for a Base* without any pointer arithmetic. Base fields live at the same offsets either way, so upcasting in C++ is genuinely free. No instructions emitted.

Multiple Inheritance and Padding

Multiple inheritance is where things get squirrelly:

cpp
class A { public: int a; };
class B { public: int b; };
class C : public A, public B { public: int c; };

Layout of C:

cpp
Offset 0: [a (4 bytes)] <- A subobject
Offset 4: [b (4 bytes)] <- B subobject
Offset 8: [c (4 bytes)] <- C's own field

Cast a C* to a B* and the compiler quietly adds 4 bytes to the pointer to land on the B subobject. That arithmetic is the hidden tax on multiple inheritance:

asm
; C *obj = new C;
; B *b_ptr = obj; // Needs pointer adjustment!
cmp QWORD PTR [rbp-8], 0 ; Null C* must stay a null B*
je .L2
mov rax, QWORD PTR [rbp-8] ; Load C pointer
add rax, 4 ; Adjust by sizeof(A) = 4
jmp .L3
.L2:
mov eax, 0
.L3:
mov QWORD PTR [rbp-16], rax ; Store as B pointer

The compare and branch are there because a null C* has to convert to a null B*, not to address 4. At -O2 the check disappears when the compiler can prove the pointer is non-null (as it can straight after a plain new).

The this Pointer

Every non-static member function carries this as a secret first parameter. Compare a member function with the equivalent free function and the trick becomes obvious:

cpp
class Vec2 {
public:
float x, y;
float length() const { return sqrt(x*x + y*y); }
};
// Equivalent free function:
float vec2_length(const Vec2 *self) { return sqrt(self->x * self->x + self->y * self->y); }

Both versions emit nearly identical assembly. The only real difference is the mangled symbol name. There's nothing magical about this; it's just a pointer passed in rdi like any other first argument.

Alignment and Padding

Objects get padded to satisfy alignment rules, exactly the way C structs do:

cpp
class Padded {
char a; // offset 0, 1 byte
// 7 bytes padding
double b; // offset 8, 8 bytes
char c; // offset 16, 1 byte
// 3 bytes padding
int d; // offset 20, 4 bytes
};
// sizeof(Padded) = 24 (not 14)

Run sizeof on it, or just read the offsets in the assembly:

asm
mov BYTE PTR [rdi], al ; a at offset 0
movsd QWORD PTR [rdi+8], xmm0 ; b at offset 8
mov BYTE PTR [rdi+16], cl ; c at offset 16
mov DWORD PTR [rdi+20], edx ; d at offset 20

Reshuffling fields to squeeze out padding is one of the easier wins:

cpp
class Compact {
double b; // offset 0, 8 bytes
int d; // offset 8, 4 bytes
char a; // offset 12, 1 byte
char c; // offset 13, 1 byte
// 2 bytes padding
};
// sizeof(Compact) = 16 (saved 8 bytes!)

Shuffle Padded into Compact yourself below, or into something worse. The vptr box adds the hidden vtable pointer a class gets once it has a virtual function; the compiler always puts it first, so leave it at the top when you tick it.

class Padded (x86-64, GCC or Clang)

0x00x18
OffsetFieldSizeNotes
0x0 (0)char a1
0x1 (1)padding7
0x8 (8)double b8
0x10 (16)char c1
0x11 (17)padding3
0x14 (20)int d4

sizeof = 24 bytes, 10 of them padding; alignment 8.

Reorder the fields and watch the padding change.

  1. char a
  2. double b
  3. char c
  4. int d

The Bottom Line

Strip a C++ class back to the metal and what's left is a C struct with auto-called constructors and destructors, plus a name-mangling scheme that gives you overloading. The this pointer is just a function argument. Member access is a constant offset added to a base register. The one feature that genuinely costs you at runtime is virtual, which puts a vtable pointer on every instance. The rest is compile-time bookkeeping that doesn't make it into the binary.