Why is the calling constructor not called when instantiating through the factory metaclass class?

I am trying to create what, as I understand it, is a Factory class in Delphi 2007. I want to pass a type of a derived class to a function and build an object of this class type.

I found some good references, such as How can I create a Delphi object from a class reference and enforce constructor execution? but I still can't get it to work perfectly right. In the example below, I cannot force it to call a derived constructor, although the debugger tells me that oClass is TMyDerived.

I think I am confused by something fundamental here and may use some kind of explanation. Thanks.

program ClassFactoryTest; {$APPTYPE CONSOLE} uses SysUtils; // BASE CLASS type TMyBase = class(TObject) bBaseFlag : boolean; constructor Create; virtual; end; TMyBaseClass = class of TMyBase; constructor TMyBase.Create; begin bBaseFlag := false; end; // DERIVED CLASS type TMyDerived = class(TMyBase) bDerivedFlag : boolean; constructor Create; end; constructor TMyDerived.Create; begin inherited; bDerivedFlag := false; end; var oClass: TMyBaseClass; oBaseInstance, oDerivedInstance: TMyBase; begin oClass := TMyBase; oBaseInstance := oClass.Create; oClass := TMyDerived; oDerivedInstance := oClass.Create; // <-- Still calling Base Class constructor end. 
+6
source share
1 answer

You ignored specifying override in the constructor of the derived class. (I would expect a warning from the compiler about hiding the base class method.) Add this and you should see TMyDerived.Create .

 TMyDerived = class(TMyBase) bDerivedFlag : boolean; constructor Create; override; end; 

An alternative, since your constructors do not accept any parameters, is to abandon virtual constructors and simply override AfterConstruction .

+13
source

Source: https://habr.com/ru/post/887477/


All Articles