tconstructor.nim 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. discard """
  2. targets: "cpp"
  3. cmd: "nim cpp $file"
  4. output: '''
  5. 1
  6. 0
  7. 123
  8. 0
  9. 123
  10. '''
  11. """
  12. {.emit:"""/*TYPESECTION*/
  13. struct CppClass {
  14. int x;
  15. int y;
  16. CppClass(int inX, int inY) {
  17. this->x = inX;
  18. this->y = inY;
  19. }
  20. //CppClass() = default;
  21. };
  22. """.}
  23. type CppClass* {.importcpp, inheritable.} = object
  24. x: int32
  25. y: int32
  26. proc makeCppClass(x, y: int32): CppClass {.importcpp: "CppClass(@)", constructor.}
  27. #test globals are init with the constructor call
  28. var shouldCompile {.used.} = makeCppClass(1, 2)
  29. proc newCpp*[T](): ptr T {.importcpp:"new '*0()".}
  30. #creation
  31. type NimClassNoNarent* = object
  32. x: int32
  33. proc makeNimClassNoParent(x:int32): NimClassNoNarent {. constructor.} =
  34. this.x = x
  35. discard
  36. let nimClassNoParent = makeNimClassNoParent(1)
  37. echo nimClassNoParent.x #acess to this just fine. Notice the field will appear last because we are dealing with constructor calls here
  38. var nimClassNoParentDef {.used.}: NimClassNoNarent #test has a default constructor.
  39. #inheritance
  40. type NimClass* = object of CppClass
  41. proc makeNimClass(x:int32): NimClass {. constructor:"NimClass('1 #1) : CppClass(0, #1) ".} =
  42. this.x = x
  43. #optinially define the default constructor so we get rid of the cpp warn and we can declare the obj (note: default constructor of 'tyObject_NimClass__apRyyO8cfRsZtsldq1rjKA' is implicitly deleted because base class 'CppClass' has no default constructor)
  44. proc makeCppClass(): NimClass {. constructor: "NimClass() : CppClass(0, 0) ".} =
  45. this.x = 1
  46. let nimClass = makeNimClass(1)
  47. var nimClassDef {.used.}: NimClass #since we explictly defined the default constructor we can declare the obj
  48. #bug: 22662
  49. type
  50. BugClass* = object
  51. x: int # Not initialized
  52. proc makeBugClass(): BugClass {.constructor.} =
  53. discard
  54. proc main =
  55. for i in 0 .. 1:
  56. var n = makeBugClass()
  57. echo n.x
  58. n.x = 123
  59. echo n.x
  60. main()