Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class helper doesn't override ancestor's virtual methods

I always understood class helpers as extension classes, or partial classes. They act like an expand for the code of the original base class. If I copied the interface part of code and add it to the base class and do so for the implementation too, the code will run perfectly the same way as with the helper. This let me always understand the polymorphisme in helpers and why they can't override methods from the base class and such things.

But I found that this is not completely true, because if so then why they don't allow to override methods of an ancestor -parent of the base- class?

Here is an example of what I mean(I will only put the code for the headers without implementation code):

type
  TAncestor = class
  public 
    procedure Test; virtual;
  end;

  TBase = class(TAncestor)
  public 
  end;

So why the next code is not right :

THelper = class helper of TBase
public 
  procedure Test; override;
end;

The error that I have is :

Method 'Test' not found in base class!

like image 366
ZORRO_BLANCO Avatar asked Dec 17 '22 18:12

ZORRO_BLANCO


2 Answers

Class helpers can not modify the original class layout. That is why they can't add fields (but they can add non-virtual non-dynamic methods, of course). The extra methods are not really part of the helped class, they merely tell the compiler that each time it sees that method, it should pretend it was part of the original class

But overriding a virtual method would mean modifying the virtual method table of the helped class, and that is not possible either. The compiler could of course create a new VMT (an array of pointers to code) with the override in it, but, because a class helper does not modify the "helped" instance, it can't simply replace the VMT pointer in the instance with the new one. So the instance cannot be made to refer to the new VMT.

There is only one way to override a virtual method: by inheritance.

Documentation says:

A helper type may not declare instance data, but class fields are allowed.

like image 198
Rudy Velthuis Avatar answered Dec 24 '22 00:12

Rudy Velthuis


try "class interception" (ggl it)
something like this its similar to c# "partial class" in delphi

type
  TPageControl = class(Vcl.ComCtrls.TPageControl)
....
like image 34
Zen Of Kursat Avatar answered Dec 24 '22 01:12

Zen Of Kursat