www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - this reference in c'tor

reply Mike <vertex gmx.at> writes:
Hi!

I know that there has to be a reason why one can't use "this" references in the
constructor. But why? I can assign members. So "this" exists in the constructor
... why does the (simplified) example below trigger the assert?

' class Foo
' {
'    public this(Foo parent)
'    {
'         assert(parent !is null);
'         children ~= new(Foo(this));
'    }
'    private Foo[] children;
' }

(Disclaimer: I know that this expamle is an infinite loop)

I need to build a tree and certain Foos need to build default childs when
they're instantiated. Having a separate construct method ... no, that's just
not it. The Foo c'tor should build a complete Foo instance, not half of it.

-Mike (frustrated)
Nov 25 2007
parent Mike <vertex gmx.at> writes:
I guess it's been too long for today - brain exhausted - such a stupid mistake.
That was the wrong assert in my code. So embarrassing.

Mike Wrote:

 Hi!
 
 I know that there has to be a reason why one can't use "this" references in
the constructor. But why? I can assign members. So "this" exists in the
constructor ... why does the (simplified) example below trigger the assert?
 
 ' class Foo
 ' {
 '    public this(Foo parent)
 '    {
 '         assert(parent !is null);
 '         children ~= new(Foo(this));
 '    }
 '    private Foo[] children;
 ' }
 
 (Disclaimer: I know that this expamle is an infinite loop)
 
 I need to build a tree and certain Foos need to build default childs when
they're instantiated. Having a separate construct method ... no, that's just
not it. The Foo c'tor should build a complete Foo instance, not half of it.
 
 -Mike (frustrated)
Nov 25 2007