Nested Classes with inheritance
user1234
user1234 at 12.de
Sat Mar 19 00:16:48 UTC 2022
On Saturday, 19 March 2022 at 00:05:54 UTC, Salih Dincer wrote:
> Greetings to all...
>
> There are nested classes as below. But beware, there's also
> inheritance, extra! If you construct ```Bar b``` from main(),
> it's okay. But if declare the constructor in Foo(), the program
> crashes with a segmentation error.
>
> Is this not legal? Like two mirrors are facing each other, that
> I do?
>
> ```d
> class Foo
> {
> Bar b;
> int i;
>
> this(int n)
> {
> this.i = n;
> //this.b = new Bar(this.i); // compiles but crashes
> }
>
> class Bar : Foo
> {
> int i;
>
> this(int n)
> {
> this.i = n;
> super(this.i);
> }
>
> }
> }
>
> void main()
> {
> auto foo = new Foo(1);
> auto bar = foo.new Bar(1);
> foo.b = bar;
>
> assert(foo.i == foo.b.i);
> }
> ```
> SDB at 79
That crashes because of the creation of `Bar b` member, which
itself has a Bar b member, which itself...
One solution is to create the member depending on some condition,
example:
```d
if (typeid(this) !is typeid(Bar))
this.b = new Bar(this.i);
```
More information about the Digitalmars-d-learn
mailing list