summary refs log tree commit diff stats
path: root/doc
diff options
context:
space:
mode:
authorJuan M Gómez <info@jmgomez.me>2023-06-06 20:22:32 +0100
committerGitHub <noreply@github.com>2023-06-06 21:22:32 +0200
commit134b1890d549242169d3c5994685198d0a0bb838 (patch)
tree8cb1a1881e54b42404cf5350193d092138552d9e /doc
parent0f3d6b5a52981cc8df49120a770c20152d75ee2d (diff)
downloadNim-134b1890d549242169d3c5994685198d0a0bb838.tar.gz
documents constructor (#22013)
* documents constructor

* Apply suggestions from code review

---------

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
Diffstat (limited to 'doc')
-rw-r--r--doc/manual_experimental.md58
1 files changed, 58 insertions, 0 deletions
diff --git a/doc/manual_experimental.md b/doc/manual_experimental.md
index 25c9c1b55..4e838d65d 100644
--- a/doc/manual_experimental.md
+++ b/doc/manual_experimental.md
@@ -2206,3 +2206,61 @@ var val: int32 = 10
 NimPrinter().printConstRef(message, val)
 
 ```
+
+constructor pragma
+==================
+
+The `constructor` pragmas has two ways of being used: in conjunction with `importcpp` to import a C++ constructor and as a way to declare constructors that works similarly to `virtual`. 
+
+Consider:
+
+```nim
+
+type Foo* = object
+  x: int32
+
+proc makeFoo(x: int32): Foo {.constructor.} =
+  this.x = x
+
+```
+
+It forward declares the constructor in the type definition. When the constructor has parameters, it also generates a default constructor. 
+Notice, inside the body of the constructor one has access to `this` which is of the type `ptr Foo`. No `result` variable is available.
+
+Like `virtual`, `constructor` also supports a syntax that allows to express C++ constraints. 
+
+For example:
+
+```nim
+
+
+{.emit:"""/*TYPESECTION*/
+struct CppClass {
+  int x;
+  int y;
+  CppClass(int inX, int inY) {
+    this->x = inX;
+    this->y = inY;
+  }
+  //CppClass() = default; 
+};
+""".}
+
+type 
+  CppClass* {.importcpp, inheritable.} = object
+    x: int32
+    y: int32
+  NimClass* = object of CppClass
+
+proc makeNimClass(x: int32): NimClass {.constructor:"NimClass('1 #1) : CppClass(0, #1)".} =
+  this.x = x
+
+# Optional: define the default constructor explicitly
+proc makeCppClass(): NimClass {.constructor: "NimClass() : CppClass(0, 0)".} = 
+  this.x = 1
+
+```
+
+In the example above `CppClass` has a deleted default constructor. Notice how by using the constructor syntax, one can call the appropiate constructor. 
+
+Notice when calling constructor in a global variable, it will be called before `NimMain` meaning Nim is not fully initialized.
\ No newline at end of file