Debian Codegraph @

src/test/01-Basic/236-ctors-basic.ck

raw
1 // specifying and overloading class constructors
2 // requires chuck-1.5.2.0 or higher
3
4 // a class
5 class Foo
6 {
7 // a member variable (this will be initialized before
8 // any actual constructors, as Foo's "pre-constructor")
9 1 => int num;
10
11 // constructor 1 "default"
12 fun @construct()
13 {
14 2 => num;
15 <<< "constructor 1:", num >>>;
16 }
17
18 // constructor 2
19 fun @construct( int x )
20 {
21 x => num;
22 <<< "constructor 2:", x >>>;
23 }
24
25 // constructor 3
26 fun void Foo( int x, int y )
27 {
28 x*y => num;
29 <<< "constructor 3:", x, y >>>;
30 }
31
32 // constructor 4 (okay to omit void return type)
33 fun Foo( int x, int y, int z )
34 {
35 x*y*z => num;
36 <<< "constructor 4:", x, y, z >>>;
37 }
38 }
39
40 // declare a Foo, invoke constructor 1
41 Foo f0;
42 // declare a Foo, invoke constructor 1
43 Foo f1();
44 // declare a Foo, invoke constructor 2
45 Foo f2(15);
46 // instantiate a Foo, invoke constructor 3
47 new Foo(8,9) @=> Foo @ f3;
48 // instantiate a Foo, invoke constructor 4
49 new Foo(10,11,12) @=> Foo @ f4;
50
51 // print
52 <<< f0.num, f1.num, f2.num, f3.num, f4.num >>>;