Polymorphism? Passing arguments

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Nov 4 02:11:35 UTC 2017


On Saturday, November 04, 2017 01:52:06 Martin via Digitalmars-d-learn 
wrote:
> Thank you for the answer
>
> On Saturday, 4 November 2017 at 01:35:41 UTC, Adam D. Ruppe wrote:
> > Why are these ref?
> > Just taking ref away from both of those will likely fix your
> > problems.
>
> because without it i get the error "Program exited with code -11"
>
> The thing is, somwhere deeper in `setRelation` i call two
> functions:
> ```
> public void addChild(ref Node child) {
>    this.children ~= &child;
> }
>
> public void setParent(ref Node parent) {
>    this.parent = &parent;
> }
> ```

Okay, classes are reference types in D just like they are in Java or C#.
They do not live on the stack like they do in C++ (for that, you'd use a
struct, which has no inheritance). Class references are basically pointers.
Taking the address of a class reference is taking the address of the
variable on the stack. If T is a class, then

T foo = getSomeT();
T* bar = &foo;

in D would be more or less equivalent to this in C++:

T* foo = getSomeT();
T** bar = &foo;

By making the parameter ref, you are then getting the address of the class
reference in the caller, whereas without it, you're getting the address of
the class reference of the callee, and that then goes away when the function
exits - which is why things blow up on you. But they'll blow up the same way
once the variable in the class reference that you passed in goes out of
scope, and you try to use the addresses that you stored.

If you ever use & with a class in D, you're almost certainly doing something
wrong.

If typeof(this.parent) is Node, then setParent should be able to just accept
the Node without ref and assign it to this.parent, and this.parent is then
going to be pointing to the same object that the Node you passed to
setParent was pointing to. There should be no need for pointers or &.

I would suggest that you read this online book:

http://ddili.org/ders/d.en/index.html

It should help you with all of the basic stuff in D like this. If you want
to know about classes specifically, then you can skip straight to the
chapter on classes:

http://ddili.org/ders/d.en/class.html

but I expect that you'll benefit from reading the whole thing.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list