[fpc-pascal] casting interfaces and objects
post at joaomorais.com.br
Sun May 18 22:54:46 CEST 2008
Marc Santhoff wrote:
> 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
> procedure Register( obsv: IObserver );
> procedure NotifyObservers(param: TParameter);
> fObservers: TFPObjectList;
> procedure TObservable.Register( obsv: IObserver );
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.
> Is there a better method of handling this case?
Use TInterfaceList or IInterfaceList.
> 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.
> Smth. like this:
> IObserver = Interface
> procedure Notify( param: TParameter );
> TObserver = class
> procedure Notify( param: TParameter ); virtual; abstract;
> Is it legal to use one or the other when e.g. handing over an observer
> to a method having an IObserver as argument?
> fpc-pascal maillist - fpc-pascal at lists.freepascal.org
More information about the fpc-pascal