[fpc-pascal] class inheritance and type incompatibility

Sven Barth pascaldragon at googlemail.com
Sun Sep 29 11:06:50 CEST 2013


On 29.09.2013 05:49, Xiangrong Fang wrote:
> 2013/9/28 Sven Barth <pascaldragon at googlemail.com
> <mailto:pascaldragon at googlemail.com>>
>
>     On second sight your solution is not correct, because you are using
>     Clone inside your parent class which would not use the (non-virtual)
>     Clone you created.
>
>     I've now played around with 2.6.2 myself and this should solve this
>     problem:
>
>     === code begin ===
>
>     type
>        generic TTree<T> = class
>        private type
>          TSelfType = TTree;
>          TSelfClass = class of TSelfType; // earlier I suggested TTree
>     which 2.6.2 does not support=== code end ===
>
>
> ​I think this solution only fixed the problem with 2.6.2 that you have
> to use TSelfType, but the logic is still not correct.
>
> Using your modified version, I try to achieve some complex Clone​
> ​strategy, for example, either one of the following:
>
> 1) the descendant has added a field other than Data that needs to be cloned;
> 2) the clone is "non-verbatim", it will multiple Data by 2 when cloning.
>
> Let's use the 2nd one as an example, the following does not work:
>
> type
>    TIntTree = class(specialize TTree<Integer>)
>    public
>      function Clone: TIntTree;
>    end;
>
> function TIntTree.Clone: TIntTree;
> begin
>    Result := TIntTree(inherited Clone);
>    Result.Data *= 2;
> end;
>
> It only multiple the ROOT node of the cloned tree, not every node.

I would suggest you to add an additional protected virtual method to 
TTree<> which is called from TTree<>.Clone and you override that in your 
descendant classes.

Regards,
Sven




More information about the fpc-pascal mailing list