[fpc-pascal] class inheritance and type incompatibility

Sven Barth pascaldragon at googlemail.com
Sat Sep 28 10:40:56 CEST 2013


On 27.09.2013 08:03, Xiangrong Fang wrote:
> Hi Sven,
>
> 2013/9/26 Sven Barth <pascaldragon at googlemail.com
> <mailto:pascaldragon at googlemail.com>>
>
>
>     As you can see you are constructing a TTreeInteger class inside
>     TTreeInteger.Clone and nothing in the world afterwards can turn it
>     into a TTreeInt.
>
>
> ​Do you mean that casting TTreeInteger into TTreeInt is not possible
> because this is to cast a parent class into a child class?  If so, how
> this is possible (mentioned in my earlier question about avoid typecasting):
>
> type
>    TIntTree = class(specialize TTree<Integer>)
>    end;
>
> var
>    it1, it2: TIntTree;
> begin
>    ... ...
>    it2 := TIntTree(it1.FirstChild);
> end.
>
> This is also casting TTree$Integer (parent class) to TIntTree (child class)?

Depends on how you add the nodes. If you use TIntTree.Create(..., 
SomeOtherIntTree) then the class instance which is added to the FItems 
of the parent is a TIntTree. If you use TTree$Integer.Create then itwill 
be a TTree$Integer. Also see my other mail I just sent regarding your 
Clone call.

I'd suggest you to compile your code (for testing) with -CR which will 
turn all object type casts to "as" typecasts thus they will raise 
exceptions if the typecast is not possible (e.g. if you are casting a 
TTree$Integer instance to a TIntTree). This way you can find out where 
you still have problems.

Regards,
Sven



More information about the fpc-pascal mailing list