RUNE - Initial repo re-creation
[rune.git] / tests / construct.d
1 #!/usr/local/bin/rune
2 #
3 # Program to demonstrate constructors and destructors.  In particular,
4 # test constructors and destructors with stack-instantiated objects.
5 #
6 # There are three special assignment situations where constructors may run:
7 # a direct declaration on the stack, in a class definition, and as
8 # a type default.  And, of course, constructors run without any assignment
9 # too.
10 #
11 import "sys" as self;
12 import "stdio";
13
14 class fubar {
15         int x;
16         global int gx = 1;
17
18         public global constructor method void blah99()
19         {
20                 stdio.stdout->show("global constructor called (fubar)");
21                 this.gx = 2;
22         }
23
24         constructor method void blah1()
25         {
26                 stdio.stdout->show("constructor called", this.x);
27                 ++this.x;
28         }
29
30         destructor method void blah1()
31         {
32                 stdio.stdout->show("destructor called");
33                 stdio.stdout->show("result:", this.x);
34                 this.x = 0;
35         }
36 }
37
38 class fubar2 {
39         fubar   a = (x:4);
40 }
41
42 typedef fubar fubar3 = (x:50);
43
44 # note: a subclass gets its own copy of the class's global space.  The
45 # original superclass constructor is not called when we refine it so we
46 # must decide whether to call it ourselves or not.
47 #
48 subclass fubar as sfubar {
49         refine public global constructor method void blah99()
50         {
51                 stdio.stdout->show(
52                         "global constructor called (sfubar), gx should be 1:", this.gx);
53                 super.blah99(); # sets gx to 2
54                 ++this.gx;      # should be 3 now
55         }
56 }
57
58 int
59 main()
60 {
61         fubar a = (x:5);
62         fubar2 b;
63         fubar3 c;
64         fubar3 d = (x:10);
65         sfubar e;
66
67         stdio.stdout->show("There should be 2 global constructor calls");
68         ++sfubar.gx;    # should be 4 now
69         stdio.stdout->show("The value of gx in fubar should be 2: ",
70                            fubar.gx);
71         stdio.stdout->show("The value of gx in sfubar should be 4: ",
72                            sfubar.gx);
73         stdio.stdout->show("there should be 5 constructor "
74                            "and 5 destructor calls");
75         stdio.stdout->show("a.x should be 6: ",
76                            a.x);
77         stdio.stdout->show("Results should be 6, 5, 51, 11, and 1");
78 }