Polymorphic copy: Difference between revisions

→‎{{header|Ada}}: Fix modification in "07:25, 9 September 2014‎ rosettacode>Ker‎ "
(Added FreeBASIC)
(→‎{{header|Ada}}: Fix modification in "07:25, 9 September 2014‎ rosettacode>Ker‎ ")
 
Line 26:
end Base;
use Base;
 
package body Base is
function Name (X : T) return String is
Line 33:
end Name;
end Base;
 
-- The procedure knows nothing about S
procedure Copier (X : T'Class) is
Line 44:
function Clone (X : T'Class) return T_ptr is
begin
return new T'Class'(X);
end CopierClone;
 
package Derived is
type S is new T with null record;
overriding function Name (X : S) return String;
end Derived;
use Derived;
 
package body Derived is
function Name (X : S) return String is
begin
Line 62:
Object_1 : T;
Object_2 : S;
Object_3 : T_ptr := Clone(TObject_1);
Object_4 : T_ptr := Clone(SObject_2);
begin
Copier (Object_1);
Line 69:
Put_Line ("Cloned " & Object_3.all.Name);
Put_Line ("Cloned " & Object_4.all.Name);
end Test_Polymorphic_Copy;</syntaxhighlight>
</syntaxhighlight>
The procedure Copier does not know the specific type of its argument.
Nevertheless, it creates an object Duplicate of exactly the same type. The function Clone makes a copy in the heap with the correct type and returns a pointer to it.
{{out}}
<pre>
18

edits