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.
source share