C Programming

Lesson 9 of 11

Objects

C has no built-in "object" concept, but you can build your own object system using exactly the tools you already have: structs, tagged unions, and function pointers. This is the same foundation real language runtimes (Python's CPython, Lua's VM) are built on.

C

This is the tagged union pattern from a few lessons ago, put to real use: Obj can represent any value your future language or program needs, and type tells every function which union member is actually valid right now.

Why refCount is already here

Every Obj is heap-allocated (so it can outlive the function that created it and be shared around freely), which means something has to decide when it's safe to free. That's exactly the problem the next two lessons solve, this refCount field is the first piece of a reference-counting garbage collector, and this Obj struct is what it will manage.

📝 Objects Quiz

Passing score: 70%
  1. 1.In the Obj struct, what determines which member of the "as" union is currently valid?

  2. 2.Every Obj in this design is heap-allocated so it can be shared and outlive the function that created it.

  3. 3.Combining a type tag with a union to represent any kind of value is called a tagged ____.