Alternatively, one could use a generic constructor:
    
    
    # lib.nim
    
    import typetraits
    
    type
      Element* = ref object of RootObj
        id: string
    
    proc newElement*(id: string, T: typedesc[Element] = Element): T =
      result.new
      result.id = id
      echo "Instantiated an object of type ", T.name, ", size: ", 
result[].sizeOf
    
    proc printId*(e: Element) =
      echo e.id
    
    
    # user.nim
    
    import lib
    
    type
      ElementA = ref object of Element
        n: int
    
    proc newElementA(id: string, n: int): ElementA =
      result = newElement(id, ElementA)
      result.n = n
    
    let
      e = newElement("base")
      ea = newElementA("A", 5)
    e.printId
    ea.printId
    echo ea.n
    
    
    Run

Reply via email to