[fpc-pascal] Clone a instance of object

Michael Van Canneyt michael at freepascal.org
Mon Sep 23 09:19:39 CEST 2013



On Mon, 23 Sep 2013, patspiper wrote:

> On 23/09/13 10:02, Michael Van Canneyt wrote:
>> 
>> 
>> This is wrong. You are typecasting a class reference to an object instance.
>> 
>> The following works:
>> 
>> {$mode objfpc}
>> 
>> Type
>>   TBaseObject = class(TObject)
>>   public
>>   constructor Create; virtual;
>>   function Clone:TBaseObject;
>>   end;
>>   TBaseObjectClass = Class of TBaseObject;
>> 
>> constructor TBaseObject.Create;
>> 
>> begin
>> end;
>> 
>> Function TBaseObject.Clone:TBaseObject;
>> 
>> Var
>>   C : TBaseObjectClass;
>> begin
>>   C:=TBaseObjectClass(ClassType);
>>   Result:=C.Create;
>> end;
> What would happen if Result := Self.ClassType.Create were used instead?

The wrong constructor would be called. 
Classtype is equivalend to 'Class of TObject'.

The typecast is needed to ensure that the TBaseObject.Create constructor is called.
Your basic polymorphism problem...

Michael.



More information about the fpc-pascal mailing list