Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Objects and Generics

Inheritance and Methods in Nim

Learn single inheritance with of RootObj, how Nim's method keyword dispatches at runtime, the difference from proc, and how a vtable makes it work underneath.

Nim supports object-oriented programming, but it does not push you into it. Most Nim code uses plain objects and procs. When you do need several related types that share an interface, Nim offers single inheritance and runtime dispatch through method.

This lesson builds on Objects and Tuples. The Nim code is read-only on this site; the C stand-ins show how dispatch really works in the generated code.

Declaring a hierarchy

Inheritance is opt-in: an object can only be a base if it inherits from RootObj, directly or indirectly. A child names its parent with of.

NIM
type
  Shape = ref object of RootObj
    name: string

  Circle = ref object of Shape
    radius: float

  Rect = ref object of Shape
    w, h: float

Use ref object for hierarchies. Value objects would be sliced when assigned to a base-typed variable, so dynamic dispatch needs references.

proc versus method

A proc is resolved at compile time using the static type of the arguments. A method is resolved at run time using the dynamic type of the first argument (and, by default, the others too, which is called multi-methods).

NIM
method area(s: Shape): float {.base.} =
  raise newException(CatchableError, "area not implemented")

method area(c: Circle): float = 3.14159 * c.radius * c.radius
method area(r: Rect): float = r.w * r.h

let shapes: seq[Shape] = @[Circle(name: "c", radius: 1.0),
                           Rect(name: "r", w: 2.0, h: 3.0)]
for s in shapes:
  echo s.name, " ", s.area()   # the right area runs for each

The {.base.} pragma marks the root method that children override. If you had written proc area instead, both calls would run the Shape version, because the static type of s is Shape.

Calling the parent version

Nim has no super keyword. Convert the object to its parent type and call the method on it.

NIM
method describe(s: Shape): string {.base.} = "shape " & s.name
method describe(c: Circle): string =
  procCall describe(Shape(c)) & " with radius " & $c.radius

procCall forces a non-dynamic call, which is the Nim spelling of "call the parent implementation".

What dispatch compiles to

A ref object carries a hidden type pointer. A method call looks up the right function from that type. The stand-in below does it by hand with a table of function pointers.

C C stand-in: a hand-made vtable

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Because the table is chosen when the object is created, the call vt->area picks the right function even though the loop sees only Shape. Nim does the same, with a type-id lookup instead of a pointer in each object.

Type tests and conversion

Use of to ask about the dynamic type and a cast-like conversion to use the child's fields.

NIM
let s: Shape = Circle(name: "c", radius: 2.0)
if s of Circle:
  echo Circle(s).radius

Circle(s) is checked at run time and raises ObjectConversionDefect if the object is not actually a Circle.

When not to use inheritance

Nim programmers often prefer other tools: variant objects when the set of cases is closed, generics when behavior is the same for many types, and procs stored in fields when a single behavior varies. Methods also stop the compiler from inlining calls, so avoid them in hot loops.

C C stand-in: closed set with a tag instead of a vtable

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must a base object inherit from to allow children?

    An object can have children only if it derives from RootObj.
  2. 2. When is a call to a proc resolved?

    Only methods use dynamic dispatch; procs use the static types.
  3. 3. Which pragma marks the root method that children override?

    The {.base.} pragma marks the method that child types may override.
  4. 4. How do you call the parent's implementation?

    Nim has no super; procCall with a conversion to the parent type does it.

Summary

  • Inheritance uses of, and the root must derive from RootObj.
  • method dispatches at run time; proc at compile time.
  • Mark the root method with {.base.}; use procCall for the parent version.
  • Dispatch is a table lookup, shown here with a C vtable.
  • Prefer variants or generics when they fit better.

Next: Variant Objects and Enums