From 134b1890d549242169d3c5994685198d0a0bb838 Mon Sep 17 00:00:00 2001 From: Juan M Gómez Date: Tue, 6 Jun 2023 20:22:32 +0100 Subject: documents constructor (#22013) * documents constructor * Apply suggestions from code review --------- Co-authored-by: Andreas Rumpf --- doc/manual_experimental.md | 58 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) (limited to 'doc') 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 -- cgit 1.4.1-2-gfad0