Once Again, Feature Request: Nested classes in separate scope
Steven Schveighoffer
schveiguy at yahoo.com
Tue Nov 6 07:42:28 PST 2007
"downs" <default_357-line at yahoo.de> wrote in message
news:fgpev2$rl6$4 at digitalmars.com...
> Vladimir Panteleev wrote:
>> On Tue, 06 Nov 2007 12:11:04 +0200, downs <default_357-line at yahoo.de>
>> wrote:
>>
>>> Vladimir Panteleev wrote:
>>>> I think this could be done with the announced "alias foo this;" syntax.
>>>> (just declare a Foo in Bar and import its namespace)
>>>>
>>> Yes, but part of the point of the whole thing was to avoid declaring a
>>> Foo in Bar, because that implies a circular ownership relation.
>>> --downs
>>
>> Why do you call it a "circular relation"? Foo's declaration or
>> implementation is still Bar-free.
>> And technically speaking, this is done in the same way - a nested class's
>> "parent" class is nothing but a hidden member.
>>
>
> See the example. I need a Foo that owns many Bar's, but each Bar can
> also access all methods of Foo - the idea is that the Bars can only
> exist in the _context_ of a Foo, which is I think what inner classes
> were supposed to do. Sorry if I'm misunderstanding it.
> --downs :)
Given your example, the "ownership" of the Bars by Foo isn't really
expressed.
In your example, the Bars know about Foo, but Foo does not know about Bar.
And it can't, because how can you compile code that would know about all
possible objects that use it as context? So the statement that the Foo owns
many Bars implies that the Foo must have an aggregate of Bars.
That being said, I think you are getting stuck up on the point that if a
class contains a member, it owns that member *and* all data pointed to by
the member. This isn't necessarily true, and is defined by the programmer,
not the compiler. What the class owns is a *reference*. Whether it owns
the memory pointed to by the reference or not is entirely up to you.
As for your example, I would rewrite it like this:
class Foo {
int e; this() { e=4; }
}
class Bar {
// Bar does not own foo, it only references it
Foo foo;
this(Foo f) { foo = f; assert(foo !is null);}
void test() { writefln(foo.e); }
}
void main() {
auto foo=new Foo;
auto bar=new Bar(foo); // behaves like a nested class
bar.test(); // prints 4
}
Then derived classes derive from Bar, and all is happy. It isn't possible
to create a derivative of Bar without an instance of Foo. the only
difference in code usage is the new statement, but it's not that different.
Derivatives of Bar must use their foo by referencing the foo member, but I
think that might be a Good Thing.
-Steve
More information about the Digitalmars-d
mailing list