| 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 |
13 => num; // set num to something |
| 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 |
// (using class name OR @construct is interchaneable) |
| 27 |
fun Foo( int x, int y ) |
| 28 |
{ |
| 29 |
x*y => num; |
| 30 |
<<< "constructor 3:", x, y >>>; |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
// declare a Foo, invoke constructor 1 |
| 35 |
Foo f0; |
| 36 |
// declare a Foo, invoke constructor 1 |
| 37 |
Foo f1(); |
| 38 |
// declare a Foo, invoke constructor 2 |
| 39 |
Foo f2(15); |
| 40 |
// instantiate a Foo, invoke constructor 3 |
| 41 |
new Foo(8,9) @=> Foo @ f3; |
| 42 |
|
| 43 |
// print |
| 44 |
<<< f0.num, f1.num, f2.num, f3.num >>>; |
| 45 |
|
| 46 |
// can also invoke constructor for each element in array |
| 47 |
Foo array1(2)[3]; |
| 48 |
// print each element's num |
| 49 |
for( auto f : array1 ) <<< f.num, "" >>>; |
| 50 |
|
| 51 |
// instantiate an array of Foo, invoking constructor for each |
| 52 |
new Foo(6,5)[4] @=> Foo array2[]; |
| 53 |
// print each element's num |
| 54 |
for( auto f : array2 ) <<< f.num, "" >>>; |