Polymorphic copy: Difference between revisions

Line 14:
package Base is
type T is tagged null record;
type T_ptr is access all T'Class;
function Name (X : T) return String;
end Base;
Line 30 ⟶ 31:
begin
Put_Line ("Copied " & Duplicate.Name); -- Check the copy
end Copier;
 
-- The function knows nothing about S and creates a copy on the heap
function Clone (X : T'Class) return T_ptr is
begin
return new T'Class(X);
end Copier;
 
Line 47 ⟶ 54:
Object_1 : T;
Object_2 : S;
Object_3 : T_ptr := Clone(T);
Object_4 : T_ptr := Clone(S);
begin
Copier (Object_1);
Copier (Object_2);
Put_Line ("Cloned " & Object_3.all.Name);
Put_Line ("Cloned " & Object_4.all.Name);
end Test_Polymorphic_Copy;</lang>
The procedure Copier does not know the specific type of its argument. Nevertheless it creates an object Duplicate of exactly same type. Sample output:
Line 55 ⟶ 66:
Copied T
Copied S
Cloned T
Cloned S
</pre>
 
=={{header|Aikido}}==
Aikido has a native <code>clone</code> function that creates a (deep or shallow) clone of any variable of any type.
Anonymous user