Polymorphic copy: Difference between revisions

Content added Content deleted
(add E example)
(→‎{{header|D}}: added D example)
Line 112: Line 112:
X copy = original; // copy it,
X copy = original; // copy it,
copy.identify_member(); // and check what type of member it contains
copy.identify_member(); // and check what type of member it contains
}
</lang>

=={{header|D}}==
{{works with|Tango}}

If we assume there are no data members, this will be quite short and simple:
<lang D>
import tango.io.Stdout;

class T {
char[] toString() { return "I'm the instance of T"; }
T duplicate() { return new T; }
}

class S : T {
char[] toString() { return "I'm the instance of S p: " ~ str; }

override
T duplicate() { return new S; }
}

void main ()
{
T orig = new S;
T copy = orig.duplicate;
Stdout (orig).newline;
Stdout (copy).newline; // should have 'X' at the beginning
}
</lang>

Hovever this doesn't happen often in reality.

If we want to copy data fields we should have something like copy ctor, that will
do the deep copy.
<lang D>
import tango.io.Stdout;

class T {
this(T t = null) { } // ctor that will be used for copying
char[] toString() { return "I'm the instance of T"; }
T duplicate() { return new T(this); }

int custom(int x) { return 0; }
}

class S : T {
char[] str;
this(S s = null) {
super(s);
if (s !is null)
str = s.str.dup; // do the deep-copy
else // all newly created will get that
str = "123".dup;
}
char[] toString() { return "I'm the instance of S p: " ~ str; }

override
T duplicate() { return new S(this); }

// additional proc, just to test deep-copy
override
int custom(int x) {
if (str !is null) str[0] = x;
return str is null;
}
}

void main ()
{
T orig = new S;
orig.custom('X');

T copy = orig.duplicate;
orig.custom('Y');

Stdout (orig).newline;
Stdout (copy).newline; // should have 'X' at the beginning
}
}
</lang>
</lang>