Skip to content

Instantly share code, notes, and snippets.

@stisa
Last active October 14, 2016 21:01
Show Gist options
  • Save stisa/1e318f33686c7e46ef522e8982ffbc7f to your computer and use it in GitHub Desktop.
Save stisa/1e318f33686c7e46ef522e8982ffbc7f to your computer and use it in GitHub Desktop.
## Original: https://nim-by-example.github.io/oop/
## Running the above with non ref objects errors ##
type Animal = object of RootObj
name: string
age: int
method vocalize(this: Animal): string = "..."
method ageHumanYrs(this: Animal): int = this.age
type Dog = object of Animal
method vocalize(this: Dog): string = "woof"
method ageHumanYrs(this: Dog): int = this.age * 7
type Cat = object of Animal
method vocalize(this: Cat): string = "meow"
var animals: seq[Animal] = newSeq[Animal]()
animals.add(Dog(name: "Sparky", age: 10)) # <- Error here
animals.add(Cat(name: "Mitten", age: 10))
for a in animals:
echo a.vocalize()
echo a.ageHumanYrs()
#[ Running this gives: ]
test.nim(19) test
assign.nim(96) genericAssign
assign.nim(75) genericAssignAux
assign.nim(24) genericAssignAux
assign.nim(21) genericAssignAux
assign.nim(51) genericAssignAux
SIGSEGV: Illegal storage access. (Attempt to read from nil?)
]#
## Assigning first to a var runs but has wrong results ##
type Animal = object of RootObj
name: string
age: int
method vocalize(this: Animal): string = "..."
method ageHumanYrs(this: Animal): int = this.age
type Dog = object of Animal
method vocalize(this: Dog): string = "woof"
method ageHumanYrs(this: Dog): int = this.age * 7
type Cat = object of Animal
method vocalize(this: Cat): string = "meow"
var animals: seq[Animal] = newSeq[Animal]()
var d = Dog(name: "Sparky", age: 10)
var c = Cat(name: "Mitten", age: 10)
animals.add(d)
animals.add(c)
for a in animals:
echo a.vocalize()
echo a.ageHumanYrs()
#[ This results in: ]
... -> should be woof
10 -> should be 70
... -> should be meow
10
]#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment