Delphi Make sure the class constructor is called.

This is probably a simple question, but I would like to know how to provide a call to the class constructor.

If I have the following code:

type TMyObject = class(TObject) public constructor Create;override; end; implementation constructor TMyObject.Create;override; begin inherited; //do other instantiation end; 

Delphi does not allow this - "You cannot override a static method."

What I would like to do is make sure that the object is created using my custom Create constructor and that the Create Createer constructor is not called.

My current solution to the problem is to define a unique Create CreateD construct like this:

 constructor Create(aName : String);overload; 

but the programmer can potentially call the create () method of the ancestors.

+7
source share
2 answers

You simply enter the constructor with the name of the ancestor. Once you do this, the user will not be able to create a TMyObject call to the constructor introduced in TObject . If you use code like this:

 TMyObject = class public constructor Create; end; constructor TMyObject.Create; begin // I am not calling the inherited constructor because // I do not want to. end; 

You do not use the override modifier on TMyObject.Create because the parent constructor is not virtual.

Using this scheme, the user cannot create your TMyObject using the constructor introduced in the ancestor. In this case, the ancestor is TObject , and its only constructor is TObject.Create . If the user writes this code:

 X := TMyObject.Create; 

quite obviously, the TMyObject constructor will be called, not the one introduced in TObject .


If you are afraid that users will jump through hoops to create their own class using the ancestor constructor, you can make your own material from the AfterConstruction method. This is a virtual method, so it is called even if your object is created using an ancestor type class reference:

 TMyObject = class public procedure AfterConstruction;override; end; 
+14
source

TObject.Create is not a virtual constructor, so an error.

The only ways that “other programmers” could invoke the method of creating ancestors is to deliberately jump through some hoops to do this, for example.

 var ClassRef: TClass; Obj : TObject; begin ClassRef := TMyObject; Obj := ClassRef.Create; end; 

since the new constructor will hide non-virtual TObject.Create

What you want is probably more like:

 type TMyObject = class(TObject) public constructor Create;virtual; end; implementation constructor TMyObject.Create; begin inherited; //do other instantiation end; 
+6
source

All Articles