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
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:
; 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 retThree things worth pulling out:
-
thisis a hidden first argument. The constructorPoint(int x, int y)actually has THREE parameters at the assembly level:rdiholds this,rsiholds x,edxholds y. Every non-static member function getsthisshoved in front. -
Member access is just struct offsets.
this->xis[rax+0],this->yis[rax+4]. Same instructions you'd see for plain old C struct field access. -
The class has the same layout as a C struct. A
Pointobject 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:
c++filt _ZN5PointC1Eii# Output: Point::Point(int, int)
c++filt _ZNK5Point3sumEv# Output: Point::sum() constThat 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:
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.
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:
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 automaticallyexample: 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 retThat 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:
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:
[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:
class A { public: int a; };class B { public: int b; };class C : public A, public B { public: int c; };Layout of C:
Offset 0: [a (4 bytes)] <- A subobjectOffset 4: [b (4 bytes)] <- B subobjectOffset 8: [c (4 bytes)] <- C's own fieldCast 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:
; 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 pointerThe 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:
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:
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:
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 20Reshuffling fields to squeeze out padding is one of the easier wins:
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)
| Offset | Field | Size | Notes |
|---|---|---|---|
| 0x0 (0) | char a | 1 | |
| 0x1 (1) | padding | 7 | |
| 0x8 (8) | double b | 8 | |
| 0x10 (16) | char c | 1 | |
| 0x11 (17) | padding | 3 | |
| 0x14 (20) | int d | 4 |
sizeof = 24 bytes, 10 of them padding; alignment 8.
Reorder the fields and watch the padding change.
- char a
- double b
- char c
- 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.