Polymorphic copy: Difference between revisions

Converted both D entries from D1+Tango => D2+Phobos (I can't test Tango code)
(Converted both D entries from D1+Tango => D2+Phobos (I can't test Tango code))
Line 486:
 
=={{header|D}}==
 
{{libheader|Tango}}
 
If we assume there are no data members, this will be quite short and simple:
<lang Dd>importclass tango.io.Stdout;T {
char[]override string toString() { return "I'm the instance of T"; }
 
class T {
char[] toString() { return "I'm the instance of T"; }
T duplicate() { return new T; }
}
 
class S : T {
char[]override string toString() { return "I'm the instance of S"; }
 
override T duplicate() { return new S; }
T duplicate() { return new S; }
}
 
void main () {
import std.stdio;
{
T orig = new S;
T copy = orig.duplicate();
 
Stdout writeln(orig).newline;
Stdout writeln(copy).newline;
}</lang>
{{out}}
<pre>I'm the instance of S
I'm the instance of S</pre>
 
HoveverHowever this doesn't happen often in reality. If we want to copy data fields we should have something like copy constructor, that will
 
If we want to copy data fields we should have something like copy ctor, that will
do the deep copy.
<lang Dd>importclass tango.io.Stdout;T {
this(T t = null) { } // ctorConstructor that will be used for copying.
 
char[]override string toString() { return "I'm the instance of T"; }
 
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); }
 
intbool custom(intchar xc) { return 0false; }
}
 
class S : T {
char[] str;
 
this(S s = null) {
super(s);
if (s !is null)
str = s.str.dup['1', '2', '3']; // doAll thenewly deep-copycreated will get that.
else // all newly created will get that
str = "123"s.str.dup; // Do the deep-copy.
}
 
override string toString() {
char[] toString() { return "I'm the instance of S p: " ~ cast(string)str; }
}
char[] toString() { return "I'm the instance of S p: " ~ str; }
 
override T duplicate() { return new S(this); }
T duplicate() { return new S(this); }
 
// additionalAdditional procprocedure, just to test deep-copy.
override bool custom(char c) {
int custom(int x) { if (str !is null)
if (str !is null) str[0] = xc;
return str is null;
}
}
 
void main () {
import std.stdio;
{
T orig = new S;
orig.custom('X');
 
T copy = orig.duplicate();
orig.custom('Y');
 
Stdout writeln(orig).newline;
Stdout writeln(copy).newline; // shouldShould have 'X' at the beginning.
}</lang>
{{out}}
<pre>I'm the instance of S p: Y23
I'm the instance of S p: X23</pre>
 
=={{header|E}}==