[fpc-pascal] Interface type error
Sven Barth
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 ===
program tintftest;
{$mode objfpc}
{$interfaces corba}
type
ITest1 = interface
procedure Test;
end;
ITest2 = interface(ITest1)
procedure Test2;
end;
TTest = class(TObject, ITest1, ITest2)
public
procedure ITest1.Test = ITest1Test;
procedure ITest1Test;
procedure Test;
procedure Test2;
end;
procedure TTest.Test;
begin
Writeln('Test');
end;
procedure TTest.Test2;
begin
Writeln('Test2');
end;
procedure TTest.ITest1Test;
begin
Writeln('ITest1Test');
end;
var
t: TTest;
i1: ITest1;
i2: ITest2;
begin
t := TTest.Create;
i1 := t;
i1.Test;
i2 := t;
i2.Test;
i2.Test2;
end.
=== code end ===
This will print:
=== output begin ===
ITest1Test
Test
Test2
=== 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.
Regards,
Sven
More information about the fpc-pascal
mailing list