Delphi: how to dynamically change the type of a class if just VMT differs?

97 Views Asked by At

Assume you have a TAncestorClass and its descendants TDescendantClass1 and TDescendantClass2. Also assume that the descendants differ from each other just in some differently overridden virtual methods. Otherwise all the fields are identical. That is, PHYSYCALLY the actual objects are the same, just their VMT differs.

TAncestorClass = class
  ...
  procedure VirtualProc; virtual; abstract;
  ...
end;

TDescendantClass1 = class(TAncestorClass)
  procedure VirtualProc; override;
end;

TDescendantClass2 = class(TAncestorClass)
  procedure VirtualProc; override;
end;

  

Nothing special so far.

The problem is that I want to dynamically change an already created object from TDescendantClass1 to TDescendantClass2 and vice versa, any time I need this thing. Not as ugly as it seems at first sight – as the objects are essentially the same. I just want the appropriate virtual methods to get called after each type change. Theoretically replacing the VMT (or just the zone from the VMT which differs) would be enough but this – otherwise simple and trivial hack – is extremely dirty, nobody wants to use such things in his code. But the ‘clean’ way – creating a new object with the right class, then copying and freeing the original one – is obviously out of question.

So, does somebody have a much more decent idea to do this?

0

There are 0 best solutions below