Cannot pass by reference
Ali Çehreli
acehreli at yahoo.com
Sat Nov 16 23:32:21 PST 2013
On 11/16/2013 11:21 PM, Meta wrote:
>> First, just a reminder: Classes in D are reference types so in most
>> cases there is no need for ref; it already is a reference to the
>> actual object.
>
> Just out of curiosity, what does ref Object actually do?
It allows changing the actual object that the caller had. Actually, my
previous code did demonstrate this, but it lacked some print statements:
import std.stdio;
class C
{}
class D1 : C
{}
class D2 : C
{}
void foo(ref C c)
{
writefln("foo is changing the caller's object");
c = new D2();
}
void main()
{
C c = new D1();
writefln("Before calling foo: %s", c);
foo(c);
writefln("After foo returned: %s", c);
}
The output:
Before calling foo: deneme.D1
foo is changing the caller's object
After foo returned: deneme.D2
If the classes had virtual functions, then main's object would start
behaving differently.
Ali
More information about the Digitalmars-d-learn
mailing list