Nim Easy · Lesson 1 · On the house

ref objects and inheritance

Heap objects with ref, nil, inheritance with of RootObj, and dynamic dispatch with method. Lesson 1 is free — on the house.

Lessons · Nim Easy · Lesson 1 of 10 · On the house

ref objects and inheritance

Heap objects with ref, nil, inheritance with of RootObj, and dynamic dispatch with method.

Illustration for Nim
Lesson 1 is on the house.

type Node = ref object allocates on the heap; variables hold references, so assignment shares the object. Default value is nil.

Create with Node(value: 1) (for ref types this allocates) or new(Node).

Inheritance needs a root: type Animal = ref object of RootObj then Dog = ref object of Animal.

method gives dynamic dispatch on the runtime type; proc dispatches statically. Mark the base with {.base.}.

Check runtime type with of: if a of Dog: ...; convert with Dog(a).

methods

type
  Animal = ref object of RootObj
    name: string
  Dog = ref object of Animal
  Cat = ref object of Animal
    lives: int

method speak(a: Animal): string {.base.} = a.name & " makes a sound"
method speak(d: Dog): string = d.name & " says woof"
method speak(c: Cat): string = c.name & " says meow (" & $c.lives & ")"

let pets: seq[Animal] = @[Dog(name: "rex"), Cat(name: "tom", lives: 9), Animal(name: "blob")]
for p in pets: echo p.speak
let a = pets[0]
let b = a
b.name = "max"
echo a.name, " ", a of Dog, " ", pets[1] of Dog
var empty: Animal
echo empty.isNil
Match this when you type.

Quiz

What does assignment do with ref objects?

Quiz

What provides dynamic dispatch?

Quiz

What is the default value of a ref variable?

Quiz

What does a.name print after b.name = "max"?

Check

Match the still for: ref objects and inheritance.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.