Is it possible to initialize a member field before inheriting in create?

Is it possible to initialize a member field before calling the inherited in create?

IE:

constructor TMyObject.create(AOwner: TComponent); begin fMyField := xxx; inherited end; 

instead of the usual way:

 constructor TMyObject.create(AOwner: TComponent); begin inherited fMyField := xxx; end; 

just to know if they have some kind of flaw that I have not seen ...

+7
delphi
source share
1 answer

When an instance of an instance is created, the memory is allocated and initialized by default (for example, filled with zeros), and then the constructor is called. This way, any code in the constructor is executed after initialization by default, and this will be one synchronization problem that you could imagine that you are trying to do what you are doing.

However, code like yours usually indicates a deeper perplexity in the design. How could the question arise, did you initialize the value before calling the inherited constructor? There are two reasons why I can imagine where you might be tempted to do this:

  • If the field in question is declared in your derived class, then the only way to access the ancestor code to it is to call a virtual (or dynamic) method. And to do this in the constructor is dangerous, because the object is only partially created. This is the smell of a large toxic code.

  • If the field in question is declared in ancestor classes, you can use this mechanism to pass an argument from the derived class to the ancestor. This is a rather strange way to do this. A more appropriate way would be to use the arguments in your constructor.

+11
source share

All Articles