Delphi OOP force to re-implement method from inherited class

  • A+
Category:Languages

I have a child class TChildClass that descend from TBaseClass. TBaseClass has a method function foo: string; that TChildClass must always implement!

IMyInterface = Interface(IInterface)     function foo: string; end;  TBaseClass = class(TInterfacedObject, IMyInterface)   public     function foo: string; end;  TChildClass = class(TBaseClass , IMyInterface)   public     function foo: string; end; 

i want TChildClass always implement function foo and call inherited from TBaseClass:

function TBaseClass.foo: string begin     Result := 'Hello'; end;  function TChildClass.foo: string begin     Result := inherited;      Result := Result + ' world!'; end; 

how to make it?

 


You cannot force the compiler to require the override at compile-time.

In order for TChildClass to override foo(), foo() needs to be declared as virtual in TBaseClass (but NOT also abstract, since you want TBaseClass.foo() to have a default implementation, otherwise the compiler will complain!). And, unlike with C++, Delphi does not require abstract methods to be overridden, and it allows code to create instances of abstract classes at runtime (even though calling abstract methods that have not been overridden will cause runtime errors).

However, you can validate at runtime whether TBaseClass.foo() has been overridden in a descendant or not, eg:

type   IMyInterface = Interface(IInterface)     function foo: string;   end;    TBaseClass = class(TInterfacedObject, IMyInterface)   public     function foo: string; virtual;   end;    TChildClass = class(TBaseClass, IMyInterface)   public     function foo: string; override;   end;  function TBaseClass.foo: string; type   TFoo = function: string of object; var   Impl, Base: TFoo;   ClassTBase: TClass; begin   Impl := foo;   ClassTBase := TBaseClass;   Base := TBaseClass(@ClassTBase).foo;   if TMethod(Impl).Code = TMethod(Base).Code then     raise Exception.CreateFmt('foo() not implemented in class ''%s''', [ClassName]);   Result := 'Hello'; end;  function TChildClass.foo: string; begin   Result := inherited foo;   Result := Result + ' world!'; end; 

But, there is nothing you can do to force TChildClass.foo() to call inherited, that is strictly up to TChildClass to decide on its own.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: