[fpc-pascal] casting interfaces and objects

Joao Morais post at joaomorais.com.br
Sun May 18 22:54:46 CEST 2008


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.

> 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.


Joao Morais

> Smth. like this:
> 
> IObserver = Interface
>   procedure Notify( param: TParameter );
> end;
> 
> TObserver = class
> public
>   procedure Notify( param: TParameter ); virtual; abstract;
> end;
> 
> Is it legal to use one or the other when e.g. handing over an observer
> to a method having an IObserver as argument?
> 
> TIA,
> Marc
> 
> 
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
> 




More information about the fpc-pascal mailing list