Virtual constructors

Top  Previous  Next

What is translated > Constructors > Virtual constructors

 

In Delphi constructors can be used like virtual functions in C++. This can be demonstrated at the example, which is also used in the section about class methods. 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 );

 

In side 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 TD2CObject class for C++Builder or the  TObject class for other compilers is used. The files d2c_systobj.h and d2c_systobj.cpp, where these classes are defined, are part of the Delphi2Cpp professional installation.

 

 

 

 

 

 



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content