Anonymous user
Polymorphic copy: Difference between revisions
Updated to work with Nim 1.4: replaced TObject with RootObj; added {.base.} on method "speak" for type T. Minor changes in text.
(→{{header|Phix}}: added class-based alternative) |
(Updated to work with Nim 1.4: replaced TObject with RootObj; added {.base.} on method "speak" for type T. Minor changes in text.) |
||
Line 1,383:
=={{header|Nim}}==
<lang nim>type
T = ref object of
myValue: string
S1 = ref object of T
S2 = ref object of T
method speak(x: T) {.base.} = echo "T Hello ", x.myValue
method speak(x: S1) = echo "S1 Meow ", x.myValue
method speak(x: S2) = echo "S2 Woof ", x.myValue
echo "creating initial objects of types S1, S2, and T."
var a = S1(myValue: "Green")
a.speak
Line 1,400:
u.speak
echo "Making copy of a as u
u.deepCopy(a)
u.speak
a.speak
echo "Assigning new color to u
u.myValue = "Orange"
u.speak
a.speak
echo "Assigning u to reference same object as b
u = b
u.speak
b.speak
echo "Assigning new color to u. Since u,b
u.myValue = "Yellow"
u.speak
b.speak</lang>
{{out}}
<pre>creating initial objects of types S1, S2, and T.
S1 Meow Green
S2 Woof Blue
T Hello Blue
Making copy of a as u
S1 Meow Green
S1 Meow Green
Assigning new color to u
S1 Meow Orange
S1 Meow Green
Assigning u to reference same object as b
S2 Woof Blue
S2 Woof Blue
Assigning new color to u. Since u,b
S2 Woof Yellow
S2 Woof Yellow</pre>
|