tconstructor.nim 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. discard """
  2. targets: "cpp"
  3. cmd: "nim cpp $file"
  4. output: '''
  5. 1
  6. '''
  7. """
  8. {.emit:"""/*TYPESECTION*/
  9. struct CppClass {
  10. int x;
  11. int y;
  12. CppClass(int inX, int inY) {
  13. this->x = inX;
  14. this->y = inY;
  15. }
  16. //CppClass() = default;
  17. };
  18. """.}
  19. type CppClass* {.importcpp, inheritable.} = object
  20. x: int32
  21. y: int32
  22. proc makeCppClass(x, y: int32): CppClass {.importcpp: "CppClass(@)", constructor.}
  23. #test globals are init with the constructor call
  24. var shouldCompile {.used.} = makeCppClass(1, 2)
  25. proc newCpp*[T](): ptr T {.importcpp:"new '*0()".}
  26. #creation
  27. type NimClassNoNarent* = object
  28. x: int32
  29. proc makeNimClassNoParent(x:int32): NimClassNoNarent {. constructor.} =
  30. this.x = x
  31. discard
  32. let nimClassNoParent = makeNimClassNoParent(1)
  33. echo nimClassNoParent.x #acess to this just fine. Notice the field will appear last because we are dealing with constructor calls here
  34. var nimClassNoParentDef {.used.}: NimClassNoNarent #test has a default constructor.
  35. #inheritance
  36. type NimClass* = object of CppClass
  37. proc makeNimClass(x:int32): NimClass {. constructor:"NimClass('1 #1) : CppClass(0, #1) ".} =
  38. this.x = x
  39. #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)
  40. proc makeCppClass(): NimClass {. constructor: "NimClass() : CppClass(0, 0) ".} =
  41. this.x = 1
  42. let nimClass = makeNimClass(1)
  43. var nimClassDef {.used.}: NimClass #since we explictly defined the default constructor we can declare the obj