I created a class method in a class that implements an interface, but I can't seem to define it inside of the interface.
IMyClass = interface
procedure someproc();
class function myfunc() : TMyClass; // compiler doesn't like this!
end;
TMyClass = class( TInterfacedObject, IMyClass )
public
procedure someproc();
class function myfunc() : TMyClass;
end;
I want myfunc()
to create and return an instance of TMyClass
. For example:
somefunc( TMyClass.myfunc(), ... );
creates an instance of TMyClass
and passes it into somefunc
.
I can define function myfunc() : TMyClass;
in the IMyClass interface, but if I put class
in front of it, the compiler gives me an error. If I leave it off, it gives me several other errors "E2291 Missing implementation of interface method xyz.myfunc" It just doesn't accept the same signature in the interface as in the class.
I thought I've seen this work before (class methods defined in interfaces) but maybe not.
If this isn't supported directly, how do you do it?
(I'm using Delphi XE5, in case it matters.)
To generate a new GUID value, just press Ctrl+Shift+G in the Delphi IDE. Each interface you define needs a unique Guid value. An interface in OOP defines an abstraction—a template for an actual class that will implement the interface—that will implement the methods defined by the interface.
A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements. A class may contain abstract methods, concrete methods. An interface contains only abstract methods.
In Delphi, a method is a procedure or function that performs an operation on an object. A class method is a method that operates on a class reference instead of an object reference.
Implementing an interface means to actually write some code to fulfill the description of the interface, in terms of function names, attributes and return values.
Interfaces are not classes and do not support methods marked as class
, they only support non-class
methods that are implemented and called on object instances.
What you are looking for will most likely have to be implemented as a class factory instead of using an interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With