Pages

Saturday, 30 August 2014

Difference between Virtual, Dynamic and Abstract methods in Delphi

Difference between Virtual, Dynamic and Abstract methods in Delphi

Virtual and Dynamic methods are the strong concepts of Polymorphism in Delphi. Dynamic is semantically equivalent to Virtual. Both Virtual and Dynamic directives allows a class method to be override (replaced) by a same named method in a derived class. 

You would mark a function or procedure as Virtual or Dynamic when you allow a programmer who creates a class based on your class to replace its functionality. 

Virtual and Dynamic may be followed by the Abstract directive. This modifies the effect of the Virtual and Dynamic directives. It means that the current class must not code the method - it is there only as a placeholder to remind and ensure that derived classes implement it.

Difference between Virtual and Dynamic methods in Delphi

Although Virtual and Dynamic methods appear same but there is some differnce in their internal implementation. Virtual methods are implemented with a Virtual Method Table (VMT). There is one VMT for each class. The VMT contains one entry for each virtual method in the class. And that entry is the address of the method.

This allows for very efficient calling. You simply get the address of the VMT which is located at a fixed offset from Self. Then you look up the method pointer by index and call the method.

What this does mean is that if you have a class with a lot of virtual methods, and you derive a sub-class, you will make a brand new VMT with all the virtual methods. And if you have not overridden many of them, then you'll find that the VMTs have a lot of overlap.

This used to matter in the days of 16 bit. The VMTs could take up a lot of space in the executable image (that's what is meant by code size) and you could run out of space for the VMTs. So dynamic methods were introduced. The analogue to the VMT is the dynamic method table, DMT. This is implemented differently to avoid the repetition when methods are not overridden. The downside is that calling dynamic methods is more expensive.

In modern times, since 32 bit, and especially with the very fat executables that Delphi produces, these size issues don't matter. And so all sound advice is to use virtual methods exclusively.

Abstract methods must be virtual or dynamic

Any abstract method should be virtual or dynamic. For example:

function Age: Integer; Abstract;

will not work and throw following error:

E2167 Abstract methods must be virtual or dynamic

Conclusion: Virtual methods are optimized for speed and dynamic methods are optimized for size. In most of the situations, speed is more crucial than size, so I would prefer to use Virtual methods.

No comments:

Post a Comment