Polymorphic copy: Difference between revisions
Content added Content deleted
(Converted both D entries from D1+Tango => D2+Phobos (I can't test Tango code)) |
|||
Line 486: | Line 486: | ||
=={{header|D}}== |
=={{header|D}}== |
||
{{libheader|Tango}} |
|||
If we assume there are no data members, this will be quite short and simple: |
If we assume there are no data members, this will be quite short and simple: |
||
<lang |
<lang d>class T { |
||
⚫ | |||
class T { |
|||
⚫ | |||
T duplicate() { return new T; } |
T duplicate() { return new T; } |
||
} |
} |
||
class S : T { |
class S : T { |
||
override string toString() { return "I'm the instance of S"; } |
|||
override |
override T duplicate() { return new S; } |
||
T duplicate() { return new S; } |
|||
} |
} |
||
void main () |
void main () { |
||
import std.stdio; |
|||
{ |
|||
T orig = new S; |
T orig = new S; |
||
T copy = orig.duplicate; |
T copy = orig.duplicate(); |
||
writeln(orig); |
|||
writeln(copy); |
|||
}</lang> |
}</lang> |
||
{{out}} |
|||
<pre>I'm the instance of S |
|||
I'm the instance of S</pre> |
|||
However 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. |
do the deep copy. |
||
<lang |
<lang d>class T { |
||
⚫ | |||
⚫ | |||
class T { |
|||
⚫ | |||
⚫ | |||
T duplicate() { return new T(this); } |
T duplicate() { return new T(this); } |
||
bool custom(char c) { return false; } |
|||
} |
} |
||
class S : T { |
class S : T { |
||
char[] str; |
char[] str; |
||
this(S s = null) { |
this(S s = null) { |
||
super(s); |
super(s); |
||
if (s |
if (s is null) |
||
str = |
str = ['1', '2', '3']; // All newly created will get that. |
||
else |
else |
||
str = |
str = s.str.dup; // Do the deep-copy. |
||
} |
|||
override string toString() { |
|||
⚫ | |||
} |
} |
||
⚫ | |||
override |
override T duplicate() { return new S(this); } |
||
T duplicate() { return new S(this); } |
|||
// |
// Additional procedure, just to test deep-copy. |
||
override |
override bool custom(char c) { |
||
if (str !is null) |
|||
str[0] = c; |
|||
return str is null; |
return str is null; |
||
} |
} |
||
} |
} |
||
void main () |
void main () { |
||
import std.stdio; |
|||
{ |
|||
T orig = new S; |
T orig = new S; |
||
orig.custom('X'); |
orig.custom('X'); |
||
T copy = orig.duplicate; |
T copy = orig.duplicate(); |
||
orig.custom('Y'); |
orig.custom('Y'); |
||
writeln(orig); |
|||
writeln(copy); // Should have 'X' at the beginning. |
|||
}</lang> |
}</lang> |
||
{{out}} |
|||
<pre>I'm the instance of S p: Y23 |
|||
I'm the instance of S p: X23</pre> |
|||
=={{header|E}}== |
=={{header|E}}== |