You never modify the result or return anything in `NewChildWindow`. And since 
ChildWindow is an object and not a ref object, it will initialize all its 
fields to their default values which is why cw has no children.

I think what you want to do is in line with the super constructor calls in 
normal OOP languages, but this is not possible in Nim due to object slicing 
going away and the constructor pattern in Nim (newObj) being to create objects 
in the constructor instead of modifying a parameter. The solution I can give 
you doesn't have object inheritance and is a bit more idiomatic:
    
    
    type
      Window = ref object
        title: string
        width, height: int
        children: seq[int]
      
      ChildWindow = object
        window, parent: Window
        handle: int
    
    proc newWindow*(title: string = "My New window"): Window =
      new(result)
      result.title = title
      result.width = 800
      result.height = 600
      result.children = @[]
    
    proc addChild*(parent, window: Window): ChildWindow =
      result.parent = parent
      result.window = window
      result.handle = parent.children.len + 1
      parent.children.add(result.handle)
    
    var bw = newWindow()
    var cw = bw.addChild(newWindow("My new child window"))
    echo bw.children.len # 1
    echo cw.parent.children.len # 1
    echo cw.window.title # My new child window
    
    
    Run

Reply via email to