[fpc-pascal] casting interfaces and objects

Marc Santhoff M.Santhoff at t-online.de
Sun May 18 22:39:08 CEST 2008


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;

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?

Is there a better method of handling this case?

2. Will an interface and a class with the same signature but not
explicitely implementing this interface be runtime-compatible and
interchangably usable?

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





More information about the fpc-pascal mailing list