On Saturday, 4 November 2017 at 01:22:05 UTC, Martin wrote:
`public void setRelation(ref Node parent , ref Node child)

Why are these ref?

A lot of people coming from C++ use ref in places you shouldn't use it in D. Remember, in D, a class object is implicitly ref, so doing `ref Object` is more like `Object**` or `Object&&` - often more direction than you need and want.

Just taking ref away from both of those will likely fix your problems.

setRelation(root , new Text("blah"));

In this case, it definitely will. An explicit ref in D must refer to a variable name, not just an object. Since `new Text()` has no variable name, it cannot be ref.

Why is this? Text implements Node. This is how i do it in other Languages - How can would be this possible in D?

But, even if it were legal to do what you're trying on ref semantics, this would still be broken polymorphism! Consider the following:

Text text = new Text();
Node n = text; // legal, Text implements Node
n = new Element(); // also legal, Element impls Node too

buuuut:

Text text = new Text();
Node* n = &text; // subtly different than above...
*n = new Element(); // ...because this would be bad news
// what is text now?


If the compiler allowed that pointer (or the ref, same deal), you would have overwritten a Text object with an Element, breaking the type system.


This is also the reason why a Text[] will not cast to a Node[], even though an individual Text is a Node.

Reply via email to