From d2082174c583ab6598971150a85046eab4fcc9f8 Mon Sep 17 00:00:00 2001 From: rillk500 Date: Wed, 17 Jun 2020 17:12:59 +0600 Subject: [PATCH] Classes vs. Structs in D --- lesson#17/main.d | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 lesson#17/main.d diff --git a/lesson#17/main.d b/lesson#17/main.d new file mode 100644 index 0000000..510b68f --- /dev/null +++ b/lesson#17/main.d @@ -0,0 +1,63 @@ +import std.stdio: writeln; + +// classes are a reference type, structs are a value type +class Hello { + string name; + + this(string s) { + name = s; + } + + void print() { + writeln("hello, ", name, "!"); + } + + // a func for copying an object + Hello dup() { + return new Hello(name); + } +} + +void main() { + // class initialization + Hello hello = new Hello("John"); // use -vgc flag to display GC allocations + + // allocating on the stack using "scope" keyword + //scope Hello hello = new Hello("John"); + + if(hello is null) { + writeln("Error! Could not initialize hello!"); + return; + } + + /* scope(...) { ... } expressions: + scope(success) { ... } => is executed if the scope exits successfully + scope(failure) { ... } => is executed if the scope exits due to an exception + scope(exit) { ... } => is executed regardless of the previous two cases + */ + + scope(exit) { + writeln("goodbuy..."); + } + + hello.print(); + + // making a reference + Hello ref_hello = hello; + + // making a copy + Hello copy_hello = hello.dup(); +} + + + + + + + + + + + + +