Polymorphism? Passing arguments

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Nov 4 01:40:30 UTC 2017


On Saturday, November 04, 2017 01:22:05 Martin via Digitalmars-d-learn 
wrote:
> I have a interface
> `interface Node {...}`
>
> and some classes implementing Node:
> ```
> class Text : Node {...}
> class Element : Node {...}
> ```
> and a function like this:
> `public void setRelation(ref Node parent , ref Node child) {...}`
>
> if i do this it works:
> ```
> Node root = new Element("root");
> Node text = new Text("blah");
> setRelation(root ,  text);
> ```
>
> but this does not:
> ```
> Node root = new Element("root");
> setRelation(root , new Text("blah"));
> ```
>
> >Error: function Nodes.setRelation (ref Node parent, ref Node
> >child) is not callable using argument types (Node, Text)
>
> Why is this? Text implements Node. This is how i do it in other
> Languages - How can would be this possible in D?

The problem really doesn't have anything to do with the types involved. It
has to do with ref. ref only accepts lvalues, not rvalues. So, you can't
pass it the result of new or the result of any function that returns by
value. The first example works, because you're passing variables, which are
lvalues. So, if you remove ref from parent and child, then you won't have
any problems like this, and unless you're planning on altering which objects
parent and child refer to, there's really no reason to have them be marked
with ref.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list