[fpc-pascal] casting interfaces and objects
M.Santhoff at t-online.de
Sun May 18 23:20:36 CEST 2008
Am Sonntag, den 18.05.2008, 17:54 -0300 schrieb Joao Morais:
> Marc Santhoff wrote:
> > Hi,
> > I have two questions about interface usage.
> > 1. How interfaces are to handle when casting?
> > Theoretically it should be safe to do this:
> > TObservable = class
> > public
> > procedure Register( obsv: IObserver );
> > private
> > procedure NotifyObservers(param: TParameter);
> > fObservers: TFPObjectList;
> > end;
> > procedure TObservable.Register( obsv: IObserver );
> > begin
> > fObservers.add(TObject(obsv));
> > end;
> It is safe to store, it isn't safe to use as an object -- you will need
> to cast back to IObserver to use the instance.
> > When using a cast from an interface to an object the compiler warns
> > about the class types "TObject" and "IObserver" not being related.
> > Since an implementor of in interface always will be a class type and any
> > class type at least inherits from TObject, I assume it is okay?
> No no, they are quite different.
So that's why the compiler issues a warning.
> > Is there a better method of handling this case?
> Use TInterfaceList or IInterfaceList.
That's nice, I only didn't know it until now.
> > 2. Will an interface and a class with the same signature but not
> > explicitely implementing this interface be runtime-compatible and
> > interchangably usable?
> No. You need to include the interface in the class declaration or make a
> workaround in the QueryInterface method.
Which is a pretty clear solution, it's only important to give the
programmer the opportunity to derive from a class or implement the
More information about the fpc-pascal