Implementing a Class in Assembly
Last module you watched C++ classes get lowered into assembly. Now flip it around. We're going to build a class system from scratch in x86-64 assembly: hand-roll a vtable, write the constructor and destructor as plain functions, and dispatch methods by hand. By the end the takeaway should be obvious. Classes aren't magic, just a tidy way to bundle function pointers next to data.
The Class We Will Implement
Here is the C++ class we will replicate:
class Animal {public: int legs; virtual void speak() = 0; virtual int get_legs() { return legs; } virtual ~Animal() {}};
class Dog : public Animal {public: int breed; Dog(int b) : breed(b) { legs = 4; } void speak() override; // prints "Woof!" ~Dog() override;};
class Cat : public Animal {public: Cat() { legs = 4; } void speak() override; // prints "Meow!" ~Cat() override;};Step 1: Define the Memory Layout
Each object starts with a vtable pointer, followed by member variables. The listings in this lesson are NASM syntax (qword [...], equ, resb), built with nasm -f elf64 and linked with ld:
; Object layouts:; Animal: [vtable_ptr (8)] [legs (4)] [padding (4)] = 16 bytes; Dog: [vtable_ptr (8)] [legs (4)] [breed (4)] = 16 bytes; Cat: [vtable_ptr (8)] [legs (4)] [padding (4)] = 16 bytes
VTABLE_OFFSET equ 0LEGS_OFFSET equ 8BREED_OFFSET equ 12 ; Dog only
ANIMAL_SIZE equ 16DOG_SIZE equ 16CAT_SIZE equ 16Step 2: Build the Vtables
A vtable is a static array of function pointers. Each class gets its own:
section .data
; Vtable for Dog; Each entry is an 8-byte function pointerdog_vtable: dq dog_speak ; slot 0: speak() dq animal_get_legs ; slot 1: get_legs() (inherited, not overridden) dq dog_destructor ; slot 2: ~Dog()
; Vtable for Catcat_vtable: dq cat_speak ; slot 0: speak() dq animal_get_legs ; slot 1: get_legs() (inherited) dq cat_destructor ; slot 2: ~Cat()
; Vtable slot indicesSPEAK_SLOT equ 0GET_LEGS_SLOT equ 8 ; 1 * 8 bytesDTOR_SLOT equ 16 ; 2 * 8 bytesNotice dog_vtable and cat_vtable diverge at slot 0, where each has its own speak, but share the same animal_get_legs at slot 1. That's inheritance in a nutshell: override only the slots you actually want to change.
Here's the same thing as a picture. Follow a Dog from its first eight bytes to the code that runs, then do the same for a Cat. The two arrows that land on animal_get_legs are the inheritance.
Step 3: Implement the Constructors
A constructor does three things:
- Allocate memory (or use the caller-provided address)
- Set the vtable pointer
- Initialize member variables
section .text
; dog_constructor: initialize a Dog object; Input: rdi = pointer to allocated memory, esi = breed; Output: none (modifies the object in place)dog_constructor: ; Set vtable pointer lea rax, [rel dog_vtable] mov qword [rdi+VTABLE_OFFSET], rax
; Set legs = 4 mov dword [rdi+LEGS_OFFSET], 4
; Set breed mov dword [rdi+BREED_OFFSET], esi
ret
; cat_constructor: initialize a Cat object; Input: rdi = pointer to allocated memorycat_constructor: ; Set vtable pointer lea rax, [rel cat_vtable] mov qword [rdi+VTABLE_OFFSET], rax
; Set legs = 4 mov dword [rdi+LEGS_OFFSET], 4
retThe C++ compiler emits exactly this dance. Stash the vtable pointer, then run the field initialisers. That vtable-pointer write is the quiet part that makes polymorphism work at all.
Step 4: Implement the Methods
section .data woof_msg: db "Woof!", 10 woof_len equ $ - woof_msg meow_msg: db "Meow!", 10 meow_len equ $ - meow_msg dtor_dog_msg: db "Dog destroyed", 10 dtor_dog_len equ $ - dtor_dog_msg dtor_cat_msg: db "Cat destroyed", 10 dtor_cat_len equ $ - dtor_cat_msg
section .text
; dog_speak: Dog::speak(); Input: rdi = 'this' pointerdog_speak: ; We ignore 'this' here since we just print a fixed string mov rax, 1 mov rdi, 1 lea rsi, [rel woof_msg] mov rdx, woof_len syscall ret
; cat_speak: Cat::speak(); Input: rdi = 'this' pointercat_speak: mov rax, 1 mov rdi, 1 lea rsi, [rel meow_msg] mov rdx, meow_len syscall ret
; animal_get_legs: shared implementation for Animal::get_legs(); Input: rdi = 'this' pointer; Output: eax = number of legsanimal_get_legs: mov eax, dword [rdi+LEGS_OFFSET] ret
; dog_destructor: Dog::~Dog(); Input: rdi = 'this' pointerdog_destructor: push rdi mov rax, 1 mov rdi, 1 lea rsi, [rel dtor_dog_msg] mov rdx, dtor_dog_len syscall pop rdi ret
; cat_destructor: Cat::~Cat()cat_destructor: push rdi mov rax, 1 mov rdi, 1 lea rsi, [rel dtor_cat_msg] mov rdx, dtor_cat_len syscall pop rdi retStep 5: Virtual Dispatch
The interesting bit. Calling a virtual function through the vtable:
; call_speak: call obj->speak() using virtual dispatch; Input: rdi = pointer to any Animal-derived objectcall_speak: mov rax, qword [rdi+VTABLE_OFFSET] ; Load vtable pointer call qword [rax+SPEAK_SLOT] ; Call vtable[0] ret
; call_get_legs: call obj->get_legs() using virtual dispatch; Input: rdi = pointer to any Animal-derived object; Output: eax = number of legscall_get_legs: mov rax, qword [rdi+VTABLE_OFFSET] call qword [rax+GET_LEGS_SLOT] ret
; call_destructor: call obj->~Animal() using virtual dispatch; Input: rdi = pointer to any Animal-derived objectcall_destructor: mov rax, qword [rdi+VTABLE_OFFSET] call qword [rax+DTOR_SLOT] retSame two-instruction pattern every single time:
- Load the vtable pointer from the object
- Call the function at the right offset inside the vtable
That's the entire mechanism. The C++ compiler emits this for every virtual call you write.
Step 6: Putting It All Together
section .bss dog_obj: resb DOG_SIZE ; Space for a Dog cat_obj: resb CAT_SIZE ; Space for a Cat
section .text global _start
_start: ; Construct a Dog with breed = 42 lea rdi, [rel dog_obj] mov esi, 42 call dog_constructor
; Construct a Cat lea rdi, [rel cat_obj] call cat_constructor
; Call speak() on Dog - prints "Woof!" lea rdi, [rel dog_obj] call call_speak
; Call speak() on Cat - prints "Meow!" lea rdi, [rel cat_obj] call call_speak
; Call get_legs() on Dog lea rdi, [rel dog_obj] call call_get_legs ; eax = 4
; Destroy both objects lea rdi, [rel dog_obj] call call_destructor
lea rdi, [rel cat_obj] call call_destructor
; Exit mov rax, 60 xor rdi, rdi syscallComparing Our Implementation to C++ Compiler Output
What we wrote is structurally indistinguishable from what g++ emits. The differences are at the edges:
-
Name mangling. We picked readable names like
dog_speak. The compiler insists on_ZN3Dog5speakEv. -
Vtable header and destructors. Under the Itanium C++ ABI that
g++follows, two extra words sit just before slot 0: the offset-to-top (used bydynamic_cast<void*>and multiple inheritance) and a pointer to the class'stype_infofortypeidanddynamic_cast. The object's vptr points past them, at slot 0. A virtual destructor also takes two slots rather than one: a complete-object destructor (D1) that only runs the destructor body, and a deleting destructor (D0) that runs it and then callsoperator delete. We skipped the header and kept a single non-deleting destructor slot, which is all our statically allocated objects need. -
Thunks. Under multiple inheritance, the compiler emits "thunk" wrappers that adjust the
thispointer before jumping to the real method. We're single-inheritance, no thunks needed. -
Exception handling. The compiler bakes in
.eh_frameentries and landing pads. We didn't bother with exception support.
What This Proves
Building a class system from raw instructions makes the truth hard to miss:
- A vtable is an array of function pointers parked in the data section
- An object is a struct whose first field happens to be a vtable pointer
- A constructor is a normal function that writes that pointer and runs the field initialisers
- A virtual call is two memory loads and an indirect
call - Inheritance is just sharing vtable entries for the methods you didn't override
thisis the first argument, every time
No runtime type system. No reflection engine. No little interpreter hiding inside the binary. C++ classes are an organisational pattern, and the compiler implements them with exactly the primitives C and assembly already give you.