Inner classes - More expressiveness needed

Janice Caron caron800 at googlemail.com
Thu Oct 25 09:39:43 PDT 2007


On 10/25/07, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
> And what would you have the outer member point to? :)  It needs to point to
> an instance of the outer class, and if you have a static function, there is
> no instance of an inner or outer class.
>
> If you need a function that requires an instance of the outer class, but not
> an instance of the inner class, the function belongs in the outer class.  I
> think that is what you wanted?

Hmm... How to explain...?

OK, to start with, I had a class which looked something like this:

    class B
    {
        int n;
        private this(int n) { this.n = n; }
        static B opCall(int n) { return new B(n); }
        int f() { return 0; }
    }

    B B_Factory(int n)  { return new B(n); }

    // In another file
    auto b = B(42);
    int n = b.f;

This all worked very nicely. But then I decided to make B an inner
class, so naturally I tried just wrapping it in class A {}, to give

    class A
    {
        int m;

        class B
        {
            int n;
            private this(int n) { this.n = n; }
            static B opCall(int n) { return new B(n); }
            int f() { return m; }
        }

        B B_Factory(int n)  { return new B(n); }
    }

    // In another file
    auto a = new A;
    auto b = a.B(42);
    int n = b.f;

and this is the point at which it stopped compiling.

I guess maybe it was a dumb thing to do, using static opCall and
making the constructor private. The thing is, while the static opCall
does not compile, the standalone function B_factory() is perfectly OK
and compiles just fine. That's because B_Factory is considered to be a
member function of A, wheras A.B.opCall() isn't.

So, when you said "If you need a function that requires an instance of
the outer class, but not an instance of the inner class, the function
belongs in the outer class", you were spot on! I can't argue with
that. It just came as a bit of a surprise that wrapping a bunch of
classes inside class A() caused some static functions to stop working.



More information about the Digitalmars-d mailing list