Lack of `outer` keyword makes inner class dup implossible

Stewart Gordon smjg_1998 at yahoo.com
Sun Jul 16 08:19:04 PDT 2006


Jarrett Billingsley wrote:
> "Derek Parnell" <derek at psych.ward> wrote in message 
> news:op.tcpklel16b8z09 at ginger.vic.bigpond.net.au...
> 
>> Excuse my ignorance, but what does an inner class provide that other 
>> alternatives can't?
> 
> Well, what does a nested function provide that a separate, external function 
> doesn't?
> 
> - Encapsulation
> - Access to outer variables

Not just _access_ to outer variables, but the concept of outer variables 
in the first place.

> - Is a Cool Thing (TM) ;)

An inner class is basically syntactic sugar for a static nested class 
that includes a reference to an object of the enclosing class as one of 
its members.  For example,

     class Board {
         class Cell {
             this() {
                 ...
             }
         }
     }

is equivalent to

     class Board {
         static class Cell {
             private Board _outer;
             this(Board b) {
                 _outer = b;
                 ...
             }
         }
     }

However, when using the static nested class approach, referring to the 
whole of the 'enclosing' object, and not just to a specific member 
thereof, becomes trivial.  OTOH, to access the outer object from an 
inner class, you have to create a property in the outer class

     class Board {
         Board theBoard() { return this; }
     }

and then use it within the inner class.  This is a pinch of salt in the 
syntactic sugar that is inner classes.  An 'outer' keyword would indeed 
be nicer.

You could ask what access level outer should have.  For example, should
it be acceptable to do, from outside, something like this?

     Cell c;
     ...
     Board b = c.outer;

Stewart.



More information about the Digitalmars-d mailing list