[fpc-pascal] Interface type error
pascaldragon at googlemail.com
Sun Feb 2 15:14:57 CET 2020
Am 02.02.2020 um 12:49 schrieb Ryan Joseph via fpc-pascal:
>> On Feb 2, 2020, at 3:23 PM, Sven Barth via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
>> As I had explained in the other thread some months ago interfaces in Object Pascal mean literally that the type can be cast to the specified interfaces. Parent interfaces are *not* part of this. If you want this you need to first cast the class to IClassName2, then the "interface inheritance" mechanism can take over.
> Hmm, isn't that inconsistent given how classes work? if TClassName implements IClassName2 then doesn't it also implement IClassName1 by definition?
You mix inheritance with interface implementation. They are conceptully
*not* the same even if they use a similar syntax. Thus they can (and do)
behave differently. And that means that you can cast a class instance
only if that interface is explicitely implemented.
Look at the following code:
=== code begin ===
ITest1 = interface
ITest2 = interface(ITest1)
TTest = class(TObject, ITest1, ITest2)
procedure ITest1.Test = ITest1Test;
t := TTest.Create;
i1 := t;
i2 := t;
=== code end ===
This will print:
=== output begin ===
=== output end ===
A class is in no way obliged to implement a interface in the same way as
an descendant interface.
This might appear like an obstacle in some case but in the contrary
declaring it explicitely allows for much more flexibility. Especially
when you're dealing with more complex interface hierarchies.
More information about the fpc-pascal