Polymorphic copy: Difference between revisions

Content added Content deleted
Line 14: Line 14:
package Base is
package Base is
type T is tagged null record;
type T is tagged null record;
type T_ptr is access all T'Class;
function Name (X : T) return String;
function Name (X : T) return String;
end Base;
end Base;
Line 30: Line 31:
begin
begin
Put_Line ("Copied " & Duplicate.Name); -- Check the copy
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;
end Copier;


Line 47: Line 54:
Object_1 : T;
Object_1 : T;
Object_2 : S;
Object_2 : S;
Object_3 : T_ptr := Clone(T);
Object_4 : T_ptr := Clone(S);
begin
begin
Copier (Object_1);
Copier (Object_1);
Copier (Object_2);
Copier (Object_2);
Put_Line ("Cloned " & Object_3.all.Name);
Put_Line ("Cloned " & Object_4.all.Name);
end Test_Polymorphic_Copy;</lang>
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:
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: Line 66:
Copied T
Copied T
Copied S
Copied S
Cloned T
Cloned S
</pre>
</pre>

=={{header|Aikido}}==
=={{header|Aikido}}==
Aikido has a native <code>clone</code> function that creates a (deep or shallow) clone of any variable of any type.
Aikido has a native <code>clone</code> function that creates a (deep or shallow) clone of any variable of any type.