tconstructor.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. discard """
  2. targets: "cpp"
  3. cmd: "nim cpp $file"
  4. output: '''
  5. 1
  6. 0
  7. 123
  8. 0
  9. 123
  10. ___
  11. 0
  12. 777
  13. 10
  14. 123
  15. 0
  16. 777
  17. 10
  18. 123
  19. '''
  20. """
  21. {.emit:"""/*TYPESECTION*/
  22. struct CppClass {
  23. int x;
  24. int y;
  25. CppClass(int inX, int inY) {
  26. this->x = inX;
  27. this->y = inY;
  28. }
  29. //CppClass() = default;
  30. };
  31. """.}
  32. type CppClass* {.importcpp, inheritable.} = object
  33. x: int32
  34. y: int32
  35. proc makeCppClass(x, y: int32): CppClass {.importcpp: "CppClass(@)", constructor.}
  36. #test globals are init with the constructor call
  37. var shouldCompile {.used.} = makeCppClass(1, 2)
  38. proc newCpp*[T](): ptr T {.importcpp:"new '*0()".}
  39. #creation
  40. type NimClassNoNarent* = object
  41. x: int32
  42. proc makeNimClassNoParent(x:int32): NimClassNoNarent {. constructor.} =
  43. this.x = x
  44. discard
  45. let nimClassNoParent = makeNimClassNoParent(1)
  46. echo nimClassNoParent.x #acess to this just fine. Notice the field will appear last because we are dealing with constructor calls here
  47. var nimClassNoParentDef {.used.}: NimClassNoNarent #test has a default constructor.
  48. #inheritance
  49. type NimClass* = object of CppClass
  50. proc makeNimClass(x:int32): NimClass {. constructor:"NimClass('1 #1) : CppClass(0, #1) ".} =
  51. this.x = x
  52. #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)
  53. proc makeCppClass(): NimClass {. constructor: "NimClass() : CppClass(0, 0) ".} =
  54. this.x = 1
  55. let nimClass = makeNimClass(1)
  56. var nimClassDef {.used.}: NimClass #since we explictly defined the default constructor we can declare the obj
  57. #bug: 22662
  58. type
  59. BugClass* = object
  60. x: int # Not initialized
  61. proc makeBugClass(): BugClass {.constructor.} =
  62. discard
  63. proc main =
  64. for i in 0 .. 1:
  65. var n = makeBugClass()
  66. echo n.x
  67. n.x = 123
  68. echo n.x
  69. main()
  70. #bug:
  71. echo "___"
  72. type
  73. NimClassWithDefault = object
  74. x: int
  75. y = 777
  76. case kind: bool = true
  77. of true:
  78. z: int = 10
  79. else: discard
  80. proc makeNimClassWithDefault(): NimClassWithDefault {.constructor.} =
  81. discard
  82. proc init =
  83. for i in 0 .. 1:
  84. var n = makeNimClassWithDefault()
  85. echo n.x
  86. echo n.y
  87. echo n.z
  88. n.x = 123
  89. echo n.x
  90. init()