Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท CLOS Object System

CLOS Initialization, Slots and the Metaobject Protocol

Customize object creation with initialize-instance and :after methods, validate slots, define print-object, use change-class and see how the CLOS metaobject protocol works.

You can change how objects are created, printed, updated and even how classes themselves behave, because CLOS is built from the same generic functions you write. This lesson walks the common hooks first and ends with a short tour of the metaobject protocol (MOP).

CLOS code is read-only here (no Common Lisp runtime on this site). JavaScript examples are labelled stand-ins that model the creation and printing protocol.

What make-instance really does

flowchart TD
    A["make-instance"] --> B["allocate-instance"]
    B --> C["initialize-instance"]
    C --> D["shared-initialize"]
    D --> E["fill slots from initargs and initforms"]

make-instance allocates, then calls initialize-instance, which calls shared-initialize to fill the slots.

make-instance, initialize-instance and shared-initialize are all generic functions. The standard recipe for custom initialization is an :after method on initialize-instance, which runs after the slots are filled:

LISP
(defclass account ()
  ((owner :initarg :owner :reader owner)
   (balance :initarg :balance :initform 0 :accessor balance)
   (id :reader account-id)))

(defvar *next-id* 0)

(defmethod initialize-instance :after ((a account) &key)
  (setf (slot-value a 'id) (incf *next-id*))
  (when (minusp (balance a))
    (error "Initial balance cannot be negative: ~a" (balance a))))

&key is required in the lambda list so extra initargs are accepted. The :after method computes a derived slot (id) and validates input. Use :before or :around only when you need to change the initargs before slots are set.

JS Stand-in: a creation protocol with an :after step

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Required slots and defaults from other slots

To force an initarg, use an :initform that signals an error:

LISP
(defclass user ()
  ((email :initarg :email
          :initform (error "A user needs :email")
          :reader email)))

If make-instance is called without :email, the initform runs and signals. To compute one slot from another, use an :after method as above, since :initform expressions cannot see other slots.

default-initargs

:default-initargs on a class supplies initargs by default and can be overridden by subclasses:

LISP
(defclass window ()
  ((title :initarg :title :reader title)
   (width :initarg :width :reader width))
  (:default-initargs :title "Untitled" :width 640))

(defclass dialog (window) ()
  (:default-initargs :width 300))

A dialog has the default title but its own width. Unlike :initform, default initargs can differ per subclass without redefining the slot.

Printing instances readably during debugging saves time:

LISP
(defmethod print-object ((a account) stream)
  (print-unreadable-object (a stream :type t :identity t)
    (format stream "~a ~a" (owner a) (balance a))))

(make-instance 'account :owner "Ada" :balance 50)
;; prints something like #<ACCOUNT Ada 50 {1003F1C2B3}>

print-unreadable-object writes the #<...> syntax correctly, including when *print-readably* is true (it signals an error then). The identity part, an implementation-specific address, is optional.

change-class and class redefinition

A live object can switch to a different class with change-class; matching slots are kept, and new ones are initialized by update-instance-for-different-class:

LISP
(change-class *account* 'savings-account)

When you redefine a class, existing instances are migrated lazily using update-instance-for-redefined-class. Both hooks are generic functions, so you can specialize them to convert data. These features make long-running Lisp systems upgradeable while running.

Slot access protocol

slot-value calls slot-value-using-class under the hood. If a class lacks a slot, slot-missing is called, which signals an error by default. You can specialize slot-missing to implement dynamic attributes, though in modern code a hash-table slot is clearer.

A glimpse of the MOP

Classes themselves are objects: (class-of 'x) yields a standard-class instance, and defclass is a macro that calls a protocol to create one. The Metaobject Protocol (MOP, described in The Art of the Metaobject Protocol) standardizes this, and most implementations expose it through packages like sb-mop (SBCL) or the portable wrapper closer-mop. Typical uses:

LISP
(closer-mop:class-slots (find-class 'account))     ; list of slot definitions
(mapcar #'closer-mop:slot-definition-name
        (closer-mop:class-slots (find-class 'account)))
;; => (OWNER BALANCE ID)

(closer-mop:class-direct-subclasses (find-class 'animal))

You can even define your own metaclass (a subclass of standard-class) to, for example, persist slots in a database or count instances:

LISP
(defclass counted-class (standard-class) ((instances :initform 0 :accessor instance-count)))

(defmethod closer-mop:validate-superclass ((c counted-class) (s standard-class)) t)

This is advanced and rarely needed. The takeaway: object-oriented features in Common Lisp are open for modification, and ORMs and serializers rely on this.

JS Stand-in: introspecting a class description

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method is the standard place to add custom initialization after slots are filled?

    An :after method on initialize-instance runs once slots have their values, so you can validate and derive other slots.
  2. 2. How can a slot require an initarg?

    The initform is only evaluated when the initarg is missing, so an error form enforces the argument.
  3. 3. What does print-unreadable-object produce?

    It wraps your output in #< and > and handles the type and identity options.
  4. 4. What is the MOP?

    The metaobject protocol exposes the class system's own structure as objects with generic functions.

Summary

  • make-instance runs allocate-instance, initialize-instance and shared-initialize.
  • Use initialize-instance :after (with &key) for validation and derived slots.
  • :default-initargs supplies per-class defaults; an erroring initform makes an initarg required.
  • print-object with print-unreadable-object gives useful debug output.
  • change-class, class redefinition and the MOP (closer-mop) make classes introspectable and mutable.

Next: Conditions: Signaling and Handling