Polymorphic copy: Difference between revisions

Content added Content deleted
(Added FreeBASIC)
(→‎{{header|Ada}}: Fix modification in "07:25, 9 September 2014‎ rosettacode>Ker‎ ")
 
Line 26: Line 26:
end Base;
end Base;
use Base;
use Base;

package body Base is
package body Base is
function Name (X : T) return String is
function Name (X : T) return String is
Line 33: Line 33:
end Name;
end Name;
end Base;
end Base;

-- The procedure knows nothing about S
-- The procedure knows nothing about S
procedure Copier (X : T'Class) is
procedure Copier (X : T'Class) is
Line 44: Line 44:
function Clone (X : T'Class) return T_ptr is
function Clone (X : T'Class) return T_ptr is
begin
begin
return new T'Class(X);
return new T'Class'(X);
end Copier;
end Clone;


package Derived is
package Derived is
type S is new T with null record;
type S is new T with null record;
overriding function Name (X : S) return String;
overriding function Name (X : S) return String;
end Derived;
end Derived;
use Derived;
use Derived;

package body Derived is
package body Derived is
function Name (X : S) return String is
function Name (X : S) return String is
begin
begin
Line 62: Line 62:
Object_1 : T;
Object_1 : T;
Object_2 : S;
Object_2 : S;
Object_3 : T_ptr := Clone(T);
Object_3 : T_ptr := Clone(Object_1);
Object_4 : T_ptr := Clone(S);
Object_4 : T_ptr := Clone(Object_2);
begin
begin
Copier (Object_1);
Copier (Object_1);
Line 69: Line 69:
Put_Line ("Cloned " & Object_3.all.Name);
Put_Line ("Cloned " & Object_3.all.Name);
Put_Line ("Cloned " & Object_4.all.Name);
Put_Line ("Cloned " & Object_4.all.Name);
end Test_Polymorphic_Copy;</syntaxhighlight>
end Test_Polymorphic_Copy;
</syntaxhighlight>
The procedure Copier does not know the specific type of its argument.
The procedure Copier does not know the specific type of its argument.
Nevertheless it creates an object Duplicate of exactly same type.
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}}
{{out}}
<pre>
<pre>