I have already encountered this error. As far as I remember, it occurs when you
use "var" in a proc whereas the type is a "ref object". If you change this in
your example, the error disappears.
type
Animal* = ref object of RootObj
age*: int
proc init(x: Animal) =
x.age = 0
method cry(x: Animal) {.base.} =
echo "Animal is silent..."
type Mammal* = ref object of Animal
legs: int
proc init(x: Mammal) =
x.Animal.init()
x.legs = 4
method cry(x: Mammal) =
echo "Mammal is crying..."
type
Dog* = ref object of Mammal
tail: int
ears: int
proc init(x: Dog) =
x.Mammal.init()
x.tail = 1
x.ears = 2
proc newDog(): Dog =
new result
result.init
return result
method cry(x: Dog) =
echo "Dog is barking..."
proc birthsday(x: Dog) =
inc(x.age)
type
Cat* = ref object of Mammal
tail: int
ears: int
angry: bool
proc init(x: Cat) =
x.Mammal.init()
x.tail = 1
x.ears = 2
x.angry = false
proc newCat(): Cat =
new result
result.init
return result
method cry(x: Cat) =
if x.angry:
echo "Cat says: Grrr..."
else:
echo "Cat says: Mmm.."
proc main =
var s = newSeq[Animal]()
let c = newCat()
c.angry = true
s.add(c)
s.add(newDog())
Dog(s[1]).birthsday()
for a in s:
a.cry()
echo "Age: ", a.age
if a of Dog:
echo "A dog with ", Dog(a). tail, "tails"
main()
Run
I find this error very annoying as it is not easy to find the cause. And, event
if "var" is not needed here, this is nevertheless a valid construct.