root/trunk/docsrc/class.dd

Revision 2140, 26.3 kB (checked in by walter, 1 year ago)

bugzilla 1351 Discrepancies in the language specification

  • Property svn:eol-style set to native
Line 
1 Ddoc
2
3 $(SPEC_S Classes,
4
5     $(P The object-oriented features of D all come from classes. The class
6     hierarchy
7     has as its root the class Object. Object defines a minimum level of functionality
8     that each derived class has, and a default implementation for that functionality.
9     )
10
11     $(P Classes are programmer defined types. Support for classes are what
12     make D an object oriented language, giving it encapsulation, inheritance,
13     and polymorphism. D classes support the single inheritance paradigm, extended
14     by adding support for interfaces. Class objects are instantiated by reference
15     only.
16     )
17
18     $(P A class can be exported, which means its name and all its
19     non-private
20     members are exposed externally to the DLL or EXE.
21     )
22
23     $(P A class declaration is defined:
24     )
25
26 $(GRAMMAR
27 $(GNAME ClassDeclaration):
28     $(B class) $(I Identifier) $(I BaseClassList) $(I ClassBody)
29     $(LINK2 template.html#ClassTemplateDeclaration, $(I ClassTemplateDeclaration))
30
31 $(GNAME BaseClassList):
32     $(I Empty)
33     $(B :) $(I SuperClass)
34     $(B :) $(I SuperClass) $(B ,) $(I InterfaceClasses)
35     $(B :) $(I InterfaceClass)
36
37 $(GNAME SuperClass):
38     $(I Identifier)
39     $(I Protection) $(I Identifier)
40
41 $(GNAME InterfaceClasses):
42     $(I InterfaceClass)
43     $(I InterfaceClass) $(B ,) $(I InterfaceClasses)
44
45 $(GNAME InterfaceClass):
46     $(I Identifier)
47     $(I Protection) $(I Identifier)
48
49 $(GNAME Protection):
50     $(B private)
51     $(B package)
52     $(B public)
53     $(B export)
54
55 $(GNAME ClassBody):
56     $(B {) $(B })
57     $(B {) $(I ClassBodyDeclarations) $(B })
58
59 $(GNAME ClassBodyDeclarations):
60     $(I ClassBodyDeclaration)
61     $(I ClassBodyDeclaration) $(I ClassBodyDeclarations)
62
63 $(GNAME ClassBodyDeclaration):
64     $(LINK2 module.html#DeclDef, $(I DeclDef))
65     $(GLINK Invariant)
66     $(GLINK ClassAllocator)
67     $(GLINK ClassDeallocator)
68 )
69
70 Classes consist of:
71
72 $(UL
73     $(LI a super class)
74     $(LI interfaces)
75     $(LI dynamic fields)
76     $(LI static fields)
77     $(LI types)
78     $(LI $(LINK2 #member-functions, member functions)
79     $(UL
80         $(LI static member functions)
81         $(LI $(LINK2 function.html#virtual-functions, Virtual Functions))
82         $(LI $(LINK2 #synchronized-functions, Synchronized Functions))
83         $(LI $(LINK2 #constructors, Constructors))
84         $(LI $(LINK2 #destructors, Destructors))
85         $(LI $(LINK2 #StaticConstructor, Static Constructors))
86         $(LI $(LINK2 #StaticDestructor, Static Destructors))
87         $(LI $(LINK2 #SharedStaticConstructor, Shared Static Constructors))
88         $(LI $(LINK2 #SharedStaticDestructor, Shared Static Destructors))
89         $(LI $(LINK2 #invariants, Class Invariants))
90         $(LI $(LINK2 unittest.html#unittest, Unit Tests))
91         $(LI $(LINK2 #allocators, Class Allocators))
92         $(LI $(LINK2 #deallocators, Class Deallocators))
93 $(V2
94         $(LI $(LINK2 #AliasThis, Alias This)))
95     )
96     )
97 )
98
99     A class is defined:
100
101 ------
102 class Foo
103 {
104     ... members ...
105 }
106 ------
107
108     Note that there is no trailing ; after the closing } of the class
109     definition.
110     It is also not possible to declare a variable var like:
111
112 ------
113 class Foo { } var;
114 ------
115
116     Instead:
117
118 ------
119 class Foo { }
120 Foo var;
121 ------
122
123 <h3>Fields</h3>
124
125     $(P Class members are always accessed with the . operator.
126     There are no :: or -&gt;
127     operators as in C++.
128     )
129
130     $(P The D compiler is free to rearrange the order of fields in a class to
131     optimally pack them in an implementation-defined manner.
132     Consider the fields much like the local
133     variables in a function -
134     the compiler assigns some to registers and shuffles others around all to
135     get the optimal
136     stack frame layout. This frees the code designer to organize the fields
137     in a manner that
138     makes the code more readable rather than being forced to organize it
139     according to
140     machine optimization rules. Explicit control of field layout is provided
141     by struct/union
142     types, not classes.
143     )
144
145 <h3>Field Properties</h3>
146
147     $(P The $(B .offsetof) property gives the offset in bytes of the field
148     from the beginning of the class instantiation.
149     $(B .offsetof) can only be applied to
150     expressions which produce the type of
151     the field itself, not the class type:
152     )
153
154 ------
155 class Foo
156 {
157     int x;
158 }
159 ...
160 void test(Foo foo)
161 {
162     size_t o;
163
164     o = Foo.x$(B .offsetof);   // error, Foo.x needs a 'this' reference
165     o = foo.x$(B .offsetof);   // ok
166 }
167 ------
168
169 <h3>Class Properties</h3>
170
171     $(P The $(B .tupleof) property returns an $(I ExpressionTuple)
172     of all the fields
173     in the class, excluding the hidden fields and the fields in the
174     base class.
175     )
176 ---
177 class Foo { int x; long y; }
178 void test(Foo foo)
179 {
180     foo.tupleof[0] = 1;     // set foo.x to 1
181     foo.tupleof[1] = 2;     // set foo.y to 2
182     foreach (x; foo.tupleof)
183     writef(x);      // prints 12
184 }
185 ---
186
187     $(P The properties $(B .__vptr) and $(B .__monitor) give access
188     to the class object's vtbl[] and monitor, respectively, but
189     should not be used in user code.
190     )
191
192 <h3>Super Class</h3>
193
194     All classes inherit from a super class. If one is not specified,
195     it inherits from Object. Object forms the root of the D class
196     inheritance hierarchy.
197
198 <h3>$(LNAME2 member-functions, Member Functions)</h3>
199
200     $(P Non-static member functions have an extra hidden parameter
201     called $(I this) through which the class object's other members
202     can be accessed.
203     )
204
205 <h3>$(LNAME2 #synchronized-functions, Synchronized Functions)</h3>
206
207     $(P Synchronized class member functions have the storage class
208     $(CODE synchronized).
209     A static member function is synchronized on the $(I classinfo)
210     object for the class, which means that one monitor is used
211     for all static synchronized member functions for that class.
212     For non-static synchronized functions, the monitor used is
213     part of the class object. For example:
214     )
215
216 ---
217 class Foo
218 {
219    synchronized void bar() { ...statements... }
220 }
221 ---
222
223     $(P is equivalent to (as far as the monitors go):
224     )
225
226 ---
227 class Foo
228 {
229    void bar()
230    {
231        synchronized (this) { ...statements... }
232    }
233 }
234 ---
235
236     $(P Structs do not have synchronized member functions.)
237
238 <h3>$(LNAME2 constructors, Constructors)</h3>
239
240 $(GRAMMAR
241 $(GNAME Constructor):
242     $(B this) $(GLINK2 declaration, Parameters) $(GLINK2 function, FunctionBody)
243 $(V2          $(GLINK2 template, TemplatedConstructor))
244 )
245
246     $(P Members are always initialized to the
247     $(LNAME2 class-default-initializer, default initializer)
248     for their type, which is usually 0 for integer types and
249     NAN for floating point types.
250     This eliminates an entire
251     class of obscure problems that come from
252     neglecting to initialize a member in one of the constructors.
253     In the class definition,
254     there can be a static initializer to be
255     used instead of the default:
256     )
257 ------
258 class Abc
259 {
260     int a;  // default initializer for a is 0
261     long b = 7; // default initializer for b is 7
262     float f;    // default initializer for f is NAN
263 }
264 ------
265
266     This static initialization is done before any constructors are
267     called.
268     <p>
269
270     Constructors are defined with a function name of $(B this)
271     and having no return value:
272
273 ------
274 class Foo
275 {
276     $(B this)(int x)        // declare constructor for Foo
277     {   ...
278     }
279     $(B this)()
280     {   ...
281     }
282 }
283 ------
284
285     Base class construction is done by calling the base class
286     constructor by the name $(B super):
287
288 ------
289 class A { this(int y) { } }
290
291 class B : A
292 {
293     int j;
294     this()
295     {
296     ...
297     $(B super)(3);  // call base constructor A.this(3)
298     ...
299     }
300 }
301 ------
302
303     $(P Constructors can also call other constructors for the same class
304     in order to share common initializations
305     $(LNAME2 delegating-constructors, (this is called delegating constructors)):
306     )
307
308 ------
309 class C
310 {
311     int j;
312     this()
313     {
314     ...
315     }
316     this(int i)
317     {
318     $(B this)();
319     j = i;
320     }
321 }
322 ------
323
324     If no call to constructors via $(B this) or $(B super) appear
325     in a constructor, and the base class has a constructor, a call
326     to $(B super)() is inserted at the beginning of the constructor.
327     <p>
328
329     If there is no constructor for a class, but there is a constructor
330     for the base class, a default constructor of the form:
331
332 ------
333 this() { }
334 ------
335
336     $(P is implicitly generated.)
337
338     $(P Class object construction is very flexible, but some restrictions
339     apply:)
340
341     $(OL
342     $(LI It is illegal for constructors to mutually call each other:
343
344 ------
345 this() { this(1); }
346 this(int i) { this(); } // illegal, cyclic constructor calls
347 ------
348     )
349
350     $(LI If any constructor call appears inside a constructor, any
351     path through the constructor must make exactly one constructor
352     call:
353
354 ------
355 this()  { a || super(); }   // illegal
356
357 this() { (a) ? this(1) : super(); } // ok
358
359 this()
360 {
361     for (...)
362     {
363     super();    // illegal, inside loop
364     }
365 }
366 ------
367     )
368
369     $(LI It is illegal to refer to $(B this) implicitly or explicitly
370     prior to making a constructor call.)
371
372     $(LI Constructor calls cannot appear after labels (in order to make
373     it easy to check for the previous conditions in the presence of goto's).)
374
375     )
376
377     $(P Instances of class objects are created with $(I NewExpression)s:)
378
379 ------
380 A a = new A(3);
381 ------
382
383     $(P The following steps happen:)
384
385 $(OL
386     $(LI Storage is allocated for the object.
387     If this fails, rather than return $(B null), an
388     $(B OutOfMemoryException) is thrown.
389     Thus, tedious checks for null references are unnecessary.
390     )
391
392     $(LI The raw data is statically initialized using the values provided
393     in the class definition.
394     The pointer to the vtbl[] (the array of pointers to virtual functions)
395     is assigned.
396     This ensures that constructors are
397     passed fully formed objects for which virtual functions can be called.
398     This operation is equivalent to doing a memory copy of a static
399     version of the object onto the newly allocated one,
400     although more advanced compilers
401     may be able to optimize much of this away.
402     )
403
404     $(LI If there is a constructor defined for the class,
405     the constructor matching the
406     argument list is called.
407     )
408
409     $(LI If class invariant checking is turned on, the class invariant
410     is called at the end of the constructor.
411     )
412 )
413
414 <h3>$(LNAME2 destructors, Destructors)</h3>
415
416 $(GRAMMAR
417 $(GNAME Destructor):
418     $(B ~this()) $(GLINK2 function, FunctionBody)
419 )
420
421     The garbage collector calls the destructor function when the object
422     is deleted. The syntax
423     is:
424
425 ------
426 class Foo
427 {
428     ~this()     // destructor for Foo
429     {
430     }
431 }
432 ------
433
434     $(P There can be only one destructor per class, the destructor
435     does not have any parameters,
436     and has no attributes. It is always virtual.
437     )
438
439     $(P The destructor is expected to release any resources held by the
440     object.
441     )
442
443     $(P The  program can explicitly inform the garbage collector that an
444     object is no longer referred to (with the delete expression), and
445     then the garbage collector calls the destructor 
446     immediately, and adds the object's memory to the free storage.
447     The destructor is guaranteed to never be called twice.
448     )
449
450     $(P The destructor for the super class automatically gets called when
451     the destructor ends. There is no way to call the super destructor
452     explicitly.
453     )
454
455     $(P The garbage collector is not guaranteed to run the destructor
456     for all unreferenced objects. Furthermore, the order in which the
457     garbage collector calls destructors for unreference objects
458     is not specified.
459     This means that
460     when the garbage collector calls a destructor for an object of a class
461     that has
462     members that are references to garbage collected objects, those
463     references may no longer be valid. This means that destructors
464     cannot reference sub objects.
465     This rule does not apply to auto objects or objects deleted
466     with the $(I DeleteExpression), as the destructor is not being run
467     by the garbage collector, meaning all references are valid.
468     )
469
470     $(P Objects referenced from the data segment never get collected
471     by the gc.
472     )
473
474 <h3>Static Constructors</h3>
475
476 $(GRAMMAR
477 $(GNAME StaticConstructor):
478     $(B static this()) $(GLINK2 function, FunctionBody)
479 )
480
481     A static constructor is defined as a function that performs
482     initializations before the
483     $(TT main()) function gets control. Static constructors are used to
484     initialize
485     static class members
486     with values that cannot be computed at compile time.
487     <p>
488
489     Static constructors in other languages are built implicitly by using
490     member
491     initializers that can't be computed at compile time. The trouble with
492     this stems from not
493     having good control over exactly when the code is executed, for example:
494
495 ------
496 class Foo
497 {
498     static int a = b + 1;
499     static int b = a * 2;
500 }
501 ------
502
503     What values do a and b end up with, what order are the initializations
504     executed in, what
505     are the values of a and b before the initializations are run, is this a
506     compile error, or is this
507     a runtime error? Additional confusion comes from it not being obvious if
508     an initializer is
509     static or dynamic.
510     <p>
511
512     D makes this simple. All member initializations must be determinable by
513     the compiler at
514     compile time, hence there is no order-of-evaluation dependency for
515     member
516     initializations, and it is not possible to read a value that has not
517     been initialized. Dynamic
518     initialization is performed by a static constructor, defined with
519     a special syntax $(TT static this()).
520
521 ------
522 class Foo
523 {
524     static int a;       // default initialized to 0
525     static int b = 1;
526     static int c = b + a;   // error, not a constant initializer
527
528     $(B static this)()      // static constructor
529     {
530     a = b + 1;      // a is set to 2
531     b = a * 2;      // b is set to 4
532     }
533 }
534 ------
535
536     $(TT static this()) is called by the startup code before
537     $(TT main()) is called. If it returns normally
538     (does not throw an exception), the static destructor is added
539     to the list of functions to be
540     called on program termination.
541     Static constructors have empty parameter lists.
542     <p>
543
544     Static constructors within a module are executed in the lexical
545     order in which they appear.
546     All the static constructors for modules that are directly or
547     indirectly imported
548     are executed before the static constructors for the importer.
549     <p>
550
551     The $(B static) in the static constructor declaration is not
552     an attribute, it must appear immediately before the $(B this):
553
554 ------
555 class Foo
556 {
557     static this() { ... }   // a static constructor
558     static private this() { ... } // not a static constructor
559     static
560     {
561     this() { ... }      // not a static constructor
562     }
563     static:
564     this() { ... }      // not a static constructor
565 }
566 ------
567
568 <h3>Static Destructors</h3>
569
570 $(GRAMMAR
571 $(GNAME StaticDestructor):
572     $(B static ~this()) $(GLINK2 function, FunctionBody)
573 )
574
575     A static destructor is defined as a special static function with the
576     syntax $(TT static ~this()).
577
578 ------
579 class Foo
580 {
581     static ~this()      // static destructor
582     {
583     }
584 }
585 ------
586
587     A static destructor gets called on program termination, but only if
588     the static constructor
589     completed successfully.
590     Static destructors have empty parameter lists.
591     Static destructors get called in the reverse order that the static
592     constructors were called in.
593     <p>
594
595     The $(B static) in the static destructor declaration is not
596     an attribute, it must appear immediately before the $(B ~this):
597
598 ------
599 class Foo
600 {
601     static ~this() { ... }  // a static destructor
602     static private ~this() { ... } // not a static destructor
603     static
604     {
605     ~this() { ... }     // not a static destructor
606     }
607     static:
608     ~this() { ... }     // not a static destructor
609 }
610 ------
611
612 $(V2
613 <h3>Shared Static Constructors</h3>
614
615 $(GRAMMAR
616 $(GNAME SharedStaticConstructor):
617     $(B shared static this()) $(GLINK2 function, FunctionBody)
618 )
619
620     $(P Shared static constructors are executed before any $(GLINK StaticConstructor)s,
621     and are intended for initializing any shared global data.
622     )
623
624 <h3>Shared Static Destructors</h3>
625
626 $(GRAMMAR
627 $(GNAME SharedStaticDestructor):
628     $(B shared static ~this()) $(GLINK2 function, FunctionBody)
629 )
630
631     $(P Shared static destructors are executed at program termination
632     in the reverse order that
633     $(GLINK SharedStaticConstructor)s were executed.
634     )
635 )
636
637 <h3>$(LNAME2 invariants, Class Invariants)</h3>
638
639 $(GRAMMAR
640 $(GNAME Invariant):
641     $(B invariant()) $(GLINK2 statement, BlockStatement)
642 )
643
644     Class invariants are used to specify characteristics of a class that always
645     must be true (except while executing a member function). For example, a
646     class representing a date might have an invariant that the day must be 1..31
647     and the hour must be 0..23:
648
649 ------
650 class Date
651 {
652     int day;
653     int hour;
654
655     $(B invariant())
656     {
657     assert(1 <= day && day <= 31);
658     assert(0 <= hour && hour < 24);
659     }
660 }
661 ------
662
663     $(P The class invariant is a contract saying that the asserts must hold
664     true.
665     The invariant is checked when a class constructor completes,
666     at the start of the class destructor, before a public or exported
667     member is run, and after a public or exported function finishes.
668     )
669
670     $(P The code in the invariant may not call any public non-static members
671     of the
672     class, either directly or indirectly.
673     Doing so will result in a stack overflow, as the invariant will wind
674     up being called in an infinitely recursive manner.
675     )
676
677     $(P Since the invariant is called at the start of public or
678     exported members, such members should not be called from
679     constructors.
680     )
681
682 ------
683 class Foo
684 {
685     public void f() { }
686     private void g() { }
687
688     $(B invariant())
689     {
690     f();  // error, cannot call public member function from invariant
691     g();  // ok, g() is not public
692     }
693 }
694 ------
695
696     The invariant
697     can be checked when a class object is the argument to an
698     <code>assert()</code> expression, as:
699
700 ------
701 Date mydate;
702 ...
703 assert(mydate);     // check that class Date invariant holds
704 ------
705
706     Invariants contain assert expressions, and so when they fail,
707     they throw a $(TT AssertError)s.
708     Class invariants are inherited, that is,
709     any class invariant is implicitly anded with the invariants of its base
710     classes.
711     <p>
712
713     There can be only one $(I Invariant) per class.
714     <p>
715
716     When compiling for release, the invariant code is not generated, and the compiled program
717     runs at maximum speed.
718
719 <h3>$(LNAME2 allocators, Class Allocators)</h3>
720
721 $(GRAMMAR
722 $(GNAME ClassAllocator):
723     $(B new) $(GLINK2 declaration, Parameters) $(GLINK2 function, FunctionBody)
724 )
725
726     A class member function of the form:
727
728 ------
729 new(uint size)
730 {
731     ...
732 }
733 ------
734
735     is called a class allocator.
736     The class allocator can have any number of parameters, provided
737     the first one is of type uint.
738     Any number can be defined for a class, the correct one is
739     determined by the usual function overloading rules.
740     When a new expression:
741
742 ------
743 new Foo;
744 ------
745
746     is executed, and Foo is a class that has
747     an allocator, the allocator is called with the first argument
748     set to the size in bytes of the memory to be allocated for the
749     instance.
750     The allocator must allocate the memory and return it as a
751     $(TT void*).
752     If the allocator fails, it must not return a $(B null), but
753     must throw an exception.
754     If there is more than one parameter to the allocator, the
755     additional arguments are specified within parentheses after
756     the $(B new) in the $(I NewExpression):
757
758 ------
759 class Foo
760 {
761     this(char[] a) { ... }
762
763     new(uint size, int x, int y)
764     {
765     ...
766     }
767 }
768
769 ...
770
771 new(1,2) Foo(a);    // calls new(Foo.sizeof,1,2)
772 ------
773
774     $(P Derived classes inherit any allocator from their base class,
775     if one is not specified.
776     )
777
778     $(P The class allocator is not called if the instance is created
779     on the stack.
780     )
781
782     $(P See also
783     $(LINK2 memory.html#newdelete, Explicit Class Instance Allocation).
784     )
785
786 <h3>$(LNAME2 deallocators, Class Deallocators)</h3>
787
788 $(GRAMMAR
789 $(GNAME ClassDeallocator):
790     $(B delete) $(GLINK2 declaration, Parameters) $(GLINK2 function, FunctionBody)
791 )
792
793     A class member function of the form:
794
795 ------
796 delete(void *p)
797 {
798     ...
799 }
800 ------
801
802     is called a class deallocator.
803     The deallocator must have exactly one parameter of type $(TT void*).
804     Only one can be specified for a class.
805     When a delete expression:
806
807 ------
808 delete f;
809 ------
810
811     $(P is executed, and f is a reference to a class instance that has
812     a deallocator, the deallocator is called with a pointer to the
813     class instance after the destructor (if any) for the class is
814     called. It is the responsibility of the deallocator to free
815     the memory.
816     )
817
818     $(P Derived classes inherit any deallocator from their base class,
819     if one is not specified.
820     )
821
822     $(P The class allocator is not called if the instance is created
823     on the stack.
824     )
825
826     $(P See also
827     $(LINK2 memory.html#newdelete, Explicit Class Instance Allocation).
828     )
829
830 $(V2
831 <h3>$(LNAME2 AliasThis, Alias This)</h3>
832
833 $(GRAMMAR
834 $(GNAME AliasThis):
835     $(B alias) $(I Identifier) $(B this;)
836 )
837
838     $(P An $(I AliasThis) declaration names another class or struct member
839     to which any undefined lookups will be forwarded.
840     The $(I Identifier) names that member.
841     )
842
843     $(P A class or struct can be implicitly converted to the $(I AliasThis)
844     member.
845     )
846
847     $(P There is only one $(I AliasThis) allowed per class or struct.
848     )
849
850 ---
851 struct S
852 {   int x;
853     alias x this;
854 }
855
856 int foo(int i) { return i * 2; }
857
858 void test()
859 {
860     S s;
861     s.x = 7;
862     int i = -s;   // i == -7
863     i = s + 8;    // i == 15
864     i = s + s;    // i == 14
865     i = 9 + s;    // i == 16
866     i = foo(s);   // implicit conversion to int
867 }
868 ---
869 )
870
871 <h3>$(LNAME2 auto, Scope Classes)</h3>
872
873     A scope class is a class with the $(B scope) attribute, as in:
874
875 ------
876 scope class Foo { ... }
877 ------
878
879     The scope characteristic is inherited, so if any classes derived
880     from a scope class are also scope.
881     <p>
882
883     An scope class reference can only appear as a function local variable.
884     It must be declared as being $(B scope):
885
886 ------
887 scope class Foo { ... }
888
889 void func()
890 {
891     Foo f;  // error, reference to scope class must be scope
892     scope Foo g = new Foo();    // correct
893 }
894 ------
895
896     When an scope class reference goes out of scope, the destructor
897     (if any) for it is automatically called. This holds true even if
898     the scope was exited via a thrown exception.
899
900 <h3>$(LNAME2 final, Final Classes)</h3>
901
902     $(P Final classes cannot be subclassed:)
903
904 ---
905 final class A { }
906 class B : A { }  // error, class A is final
907 ---
908
909 <h2>$(LNAME2 nested, Nested Classes)</h2>
910
911     A $(I nested class) is a class that is declared inside the scope
912     of a function or another class.
913     A nested class has access to the variables and other symbols
914     of the classes and functions it is nested inside:
915
916 ------
917 class Outer
918 {
919     int m;
920
921     class Inner
922     {
923     int foo()
924     {
925         return m;   // Ok to access member of Outer
926     }
927     }
928 }
929
930 void func()
931 {   int m;
932
933     class Inner
934     {
935     int foo()
936     {
937         return m;   // Ok to access local variable m of func()
938     }
939     }
940 }
941 ------
942
943     If a nested class has the $(B static) attribute, then it can
944     not access variables of the enclosing scope that are local to the
945     stack or need a $(B this):
946
947 ------
948 class Outer
949 {
950     int m;
951     static int n;
952
953     static class Inner
954     {
955     int foo()
956     {
957         return m;   // Error, Inner is static and m needs a $(B this)
958         return n;   // Ok, n is static
959     }
960     }
961 }
962
963 void func()
964 {   int m;
965     static int n;
966
967     static class Inner
968     {
969     int foo()
970     {
971         return m;   // Error, Inner is static and m is local to the stack
972         return n;   // Ok, n is static
973     }
974     }
975 }
976 ------
977
978     Non-static nested classes work by containing an extra hidden member
979     (called the context pointer)
980     that is the frame pointer of the enclosing function if it is nested
981     inside a function, or the $(B this) of the enclosing class's instance
982     if it is nested inside a class.
983     <p>
984
985     When a non-static nested class is instantiated, the context pointer
986     is assigned before the class's constructor is called, therefore
987     the constructor has full access to the enclosing variables.
988     A non-static nested class can only be instantiated when the necessary
989     context pointer information is available:
990
991 ------
992 class Outer
993 {
994     class Inner { }
995
996     static class SInner { }
997 }
998
999 void func()
1000 {
1001     class Nested { }
1002
1003     Outer o = new Outer;    // Ok
1004     Outer.Inner oi = new Outer.Inner;   // Error, no 'this' for Outer
1005     Outer.SInner os = new Outer.SInner; // Ok
1006
1007     Nested n = new Nested;  // Ok
1008 }
1009 ------
1010
1011     While a non-static nested class can access the stack variables
1012     of its enclosing function, that access becomes invalid once
1013     the enclosing function exits:
1014
1015 ------
1016 class Base
1017 {
1018     int foo() { return 1; }
1019 }
1020
1021 Base func()
1022 {   int m = 3;
1023
1024     class Nested : Base
1025     {
1026     int foo() { return m; }
1027     }
1028
1029     Base b = new Nested;
1030
1031     assert(b.foo() == 3);   // Ok, func() is still active
1032     return b;
1033 }
1034
1035 int test()
1036 {
1037     Base b = func();
1038     return b.foo();     // Error, func().m is undefined
1039 }
1040 ------
1041
1042     If this kind of functionality is needed, the way to make it work
1043     is to make copies of the needed variables within the nested class's
1044     constructor:
1045
1046 ------
1047 class Base
1048 {
1049     int foo() { return 1; }
1050 }
1051
1052 Base func()
1053 {   int m = 3;
1054
1055     class Nested : Base
1056     {   int m_;
1057
1058     this() { m_ = m; }
1059     int foo() { return m_; }
1060     }
1061
1062     Base b = new Nested;
1063
1064     assert(b.foo() == 3);   // Ok, func() is still active
1065     return b;
1066 }
1067
1068 int test()
1069 {
1070     Base b = func();
1071     return b.foo();     // Ok, using cached copy of func().m
1072 }
1073 ------
1074
1075     $(P A $(I this) can be supplied to the creation of an
1076     inner class instance by prefixing it to the $(I NewExpression):
1077     )
1078
1079 ---------
1080 class Outer
1081 {   int a;
1082
1083     class Inner
1084     {
1085     int foo()
1086     {
1087         return a;
1088     }
1089     }
1090 }
1091
1092 int bar()
1093 {
1094     Outer o = new Outer;
1095     o.a = 3;
1096     Outer.Inner oi = $(B o).new Inner;
1097     return oi.foo();    // returns 3
1098 }
1099 ---------
1100
1101     $(P Here $(B o) supplies the $(I this) to the outer class
1102     instance of $(B Outer).
1103     )
1104
1105     $(P The property $(B .outer) used in a nested class gives the
1106     $(B this) pointer to its enclosing class. If the enclosing
1107     context is not a class, the $(B .outer) will give the pointer
1108     to it as a $(B void*) type.
1109     )
1110
1111 ----
1112 class Outer
1113 {
1114     class Inner
1115     {
1116     Outer foo()
1117     {
1118         return this.$(B outer);
1119     }
1120     }
1121
1122     void bar()
1123     {
1124     Inner i = new Inner;
1125     assert(this == i.foo());
1126     }
1127 }
1128
1129 void test()
1130 {
1131     Outer o = new Outer;
1132     o.bar();
1133 }
1134 ----
1135
1136 <h3>$(LNAME2 anonymous, Anonymous Nested Classes)</h3>
1137
1138     $(P An anonymous nested class is both defined and instantiated with
1139     a $(I NewAnonClassExpression):
1140     )
1141
1142 $(GRAMMAR
1143 $(GNAME NewAnonClassExpression):
1144     $(B new) $(GLINK ParenArgumentList)$(OPT) $(B class) $(I ParenArgumentList)$(OPT) $(GLINK SuperClass)$(OPT) $(GLINK InterfaceClasses)$(OPT) $(GLINK ClassBody)
1145
1146 $(GNAME ParenArgumentList):
1147     $(B $(LPAREN)) $(I ArgumentList) $(B $(RPAREN))
1148 )
1149
1150     $(P which is equivalent to:
1151     )
1152
1153 ------
1154 class $(I Identifier) : $(I SuperClass) $(I InterfaceClasses)
1155     $(I ClassBody)
1156
1157 new ($(I ArgumentList)) $(I Identifier) ($(I ArgumentList));
1158 ------
1159
1160     $(P where $(I Identifier) is the name generated for the anonymous
1161     nested class.
1162     )
1163
1164 $(V2
1165 $(SECTION3 <a name="ConstClass">Const, Immutable and Shared Classes</a>,
1166     $(P If a $(I ClassDeclaration) has a $(CODE const), $(CODE immutable)
1167     or $(CODE shared)
1168     storage class, then it is as if each member of the class
1169     was declared with that storage class.
1170     If a base class is const, immutable or shared, then all classes derived
1171     from it are also const, immutable or shared.
1172     )
1173 )
1174 )
1175
1176 )
1177
1178 Macros:
1179     TITLE=Classes
1180     WIKI=Class
1181     GLINK=$(LINK2 #$0, $(I $0))
1182     GNAME=<a name=$0>$(I $0)</a>
1183     DOLLAR=$
1184     FOO=
Note: See TracBrowser for help on using the browser.