Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning interface pointers in a Delphi 6 class declaration?

Despite years of Delphi programming I just ran into a class declaration style I had never seen for a class that supports IUnknown:

TBCUnknown = class(TBCBaseObject, IUnKnown)
private
  FRefCount: integer;
  FOwner   : Pointer;
protected
  function IUnknown.QueryInterface = NonDelegatingQueryInterface;
  function IUnknown._AddRef = NonDelegatingAddRef;
  function IUnknown._Release = NonDelegatingRelease;
  function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
...

As you can see, assignments of class methods to IUnknown interface methods are being done right in the class declaration. This looks really strange to me especially since I don't see how the IUnknown methods could be assigned to, before the constructor is called. Is this some kind of compile-time shortcut for making assignments between a class's methods and the interface pointers for an interface the class accepts, that are later resolved at run-time? If someone could provide a little information on how this works and what Delphi idiom supports this kind of construct I'd like to know.

like image 732
Robert Oschler Avatar asked Nov 14 '11 15:11

Robert Oschler


2 Answers

It's called Method Resolution Clause and it allows you to specify which method actually implements the specified interface method. This means that the implementing method can have a different name than the method declared in the interface (but the method signature still has to match). Without the clause, Delphi automatically resolves the implementation methods based on their names.

In your example, the declaration means that IUnknown._AddRef is implemented by TBCUnknown.NonDelegatingAddRef and IUnknown._Release by TBCUnknown.NonDelegatingRelease.

As far as I know, this has been supported from the beginning when interface support was added to the language. You probably haven't noticed it because it's not used or needed so often.

like image 154
Ondrej Kelle Avatar answered Oct 04 '22 00:10

Ondrej Kelle


This is what is known as a Method Resolution Clause. To quote from the documentation:

You can override the default name-based mappings by including method resolution clauses in a class declaration. When a class implements two or more interfaces that have identically named methods, use method resolution clauses to resolve the naming conflicts.

like image 45
David Heffernan Avatar answered Oct 04 '22 01:10

David Heffernan