Hello,
I have seen the use of the new keyword in many examples dealing with ref object.
But many examples also don't use that keyword at all. So I am confused as to when you need to use that keyword vs not.
For example, this snippet in tutorial 2 does not use new. Why is that?
new isn't used there because this line does the object allocation & initialization for you:
student = Student(name: "Anton", age: 5, id: 2)
Basically, new is only used if you want to allocate space for a ref object. For example, if you want to rewrite that example by using new, you would do so:
type
Person = ref object of RootObj
name*: string # the * means that `name` is accessible from other modules
age: int # no * means that the field is hidden from other modules
Student = ref object of Person # Student inherits from Person
id: int # with an id field
var
student: Student
person: Person
assert(student of Student) # is true
# OLD object construction:
#student = Student(name: "Anton", age: 5, id: 2)
# NEW object construction with 'new' (equivalent to the above)
new(student)
student.name = "Anton"
student.age = 5
student.id = 2
echo student[]
Thank you.
That makes sense. So in that tutorial 2 snippet, the new equivalent must be called internally (I.e do the memory allocation) when I do student = Student(.., correct?