Virtual constructors

Top  Previous  Next

What is translated > Types > Records, Classes, Interfaces > Class > Constructors > Problems with constructors > Virtual constructors

 

A third problem with constructors in Delphi is that constructors can be used there like virtual functions in C++. This can be demonstrated at the example, which is also used in the section about class method. A class method might be called for a base class and another class derived from it:

 

pBase := TBase.Create;

pDerived1 := TDerived1.Create;

 

pDerived1->ClassMethod( pDerived1, 1 );

 

Inside of the class method a new object of the class is created:

 

class function TBase.ClassMethod(xi: Integer): Integer;

begin

  with Create do   <-- new object from virtual constructor

  begin

    Init;          <-- virtual method

    Done;

    Free;

  end;

  result := xi;

end;

 

The Init method might be virtual. In this case the Init method of TDerived1 will be called. That means, an instance of TDerived1 has been created, because ClassMethod was called for a TDerived1 object. If ClassMethod were called for a TBase object, a TBase object would have been created and TBase.Init would have been called.

 

This behavior can be reproduced, if the option to create meta classes is enabled.

 

 

 

 

 

 



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content