virtual class methods

Top  Previous  Next

What is translated > class methods > virtual class methods


The trick, which makes the static method virtual is, that an additional virtual method is called for the passed class pointer.


TDerived = class(TBase)


  class function ClassVirtual(xi: Integer): Integer; override;




class TDerived: public TBase {


  static int __fastcall vs_ClassVirtual( const TBase* xpTHIS, int xi ) const

  { return xpTHIS->vs_ClassVirtual(xpTHIS, xi); }

  virtual int __fastcall vs_ClassVirtual( const TBase* xpTHIS, int xi ) const;



The definition of the virtual class method analogous to the example of the non virtual class method demonstrates the difference:


class function TDerived.ClassVirtual(xi: Integer): Integer;


  with Create do  <-- new object from a virtual constructor






  result := xi;



Here the cast of the parameter xpTHIS to pTHIS is necessary to get the actual type. Because all overwritten virtual functions must have the same signatures, it is not possible to declare the class parameter with the type of the actual class. But as the method is called through redirection of the class pointer the typecast is guaranteed to be safe.


int __fastcall /*static*/ TDerived::vs_ClassVirtual( const TBase* xpTHIS, int xi ) const {

  int result = 0;

  const TDerived* pTHIS = (TDerived*) xpTHIS;

  /*# with Create do */


    TDerived* with1 = (TDerived*) pTHIS->Create();




      delete with1;



  result = xi;

  return result;







This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content