[fpc-pascal] Casting descendant interface variables to base
Andrew Hall
andrew.hall at shaw.ca
Mon Jan 31 07:29:43 CET 2011
A more detailed answer:
iDesc holds TDescClass as IDescInterface
iBase holds TDescClass as IDescInterface
iBaseAsBase holds TBaseClass as IBaseInterface
iBase holds the IDescInterface interface because they are compile-time compatible (the same as an ancestor object reference holding an object from a descendent class). iBaseAsBase explicitly casts the interface to the iBaseInterface - since the only class which implements this interface is TDescClass's ancestor, this interface reference must be used.
** If your declaration was changed thus: "TBaseClass = class(TInterfacedObject)" then the code would compile (exception for the iSelf assignment) but you would receive an "invalid typecast" at "iBaseAsBase := iBase as IBaseInterface" since TDescClass no longer supports IBaseInterface.
** If your declaration was changed thus: "TDescClass = class(TBaseClass, IBaseInterface, IDescInterface)" then iBaseAsBase would hold TDescClass as IBaseInterface.
iSelf holds TBaseClass as IBaseInterface
iSelfAsBase holds TBaseClass as IBaseInterface
iOtherAsBase holds TBaseClass as IBaseInterface
In all three of these variables, IBaseInterface is required - which is only implemented by TBaseClass - so (as with iBaseAsBase) they all hold the same reference.
An interface reference points to the private data structure which defines that interface and the procedure pointers to its supported methods (for the specific implementing class) - it does not point to the implementing object (Self) - it has no way to access the implementing class structure (or contained fields).
Regards Andrew.
On 30 Jan 11, at 20:37 , cobines wrote:
> Why does iBase have different value than iBaseAsBase? It seems simply
> assigning to interface variable doesn't change it to base interface, I
> have to explicitly use "as IBaseInterface". Is it correct?
>
> Basically, I'm trying to determine in CopyToInterface function if the
> parameter points to the same object as Self.
More information about the fpc-pascal
mailing list