Best way to create child class from a abstract Base class
abstract-class, delphi, delphi-xe3, polymorphism
Solution
No, that is not possible. Once a constructor has begun running, the class of object being created is fixed. An object cannot change its class, not even during construction.
You can write a factory function that takes the integer parameter and chooses which descendant class to instantiate. It would be a lot like your proposed invalid constructor, just as a standalone function or class method instead of a constructor.
You could also write a function that just returns the class, and then you can instantiate it afterward, like this:
type
TBaseClassClass = class of TBaseClass;
function GetDescendantClass(op: Integer): TBaseClassClass;
begun
case op of
1: Result := TChild1Class;
2: Result := TChild2Class;
else Assert(False);
end;
end;
var
DescendantClass: TBaseClassClass;
DescendantClass := GetDescendantClass (op);
T := DescendantClass.Create;
T.DoIt;
Using that technique, it's sometimes useful to make the constructor be virtual, but that's not a requirement.
Problem
Best way to create child class from a abstract Base class. In my project I have a base class abstract and two child class in this way. ``` TbaseClass=class public procedure Doit;virtual;abstract; procedure Calculate;virtual;abstract; Tchild1class=class(TbaseClass) .. protected procedure CalcArea;virtual; public procedure Doit;override; procedure Calculate;override; Tchild2class=class(Tchild1class) protected procedure CalcArea;override; ``` In my buttonclick code I create the needed childclass in this way, and is working. ``` ..... var T:TBaseClass; begin case OP of 1: T:=Tchild1class.Create; 2: T:=TChild2Class.Create; T.Doit; T.Calculate; end; ``` My question is the next. I can make a constructor create procedure in my base abstract class , that depending of int parameter generate the needed child class??? For Example: ``` constructor TBaseClass.Create(OP:integer); begin inherited; case OP of 1: Tchild1class.Create; ///>>>??? 2: TChild2Class.Create; //>>>>??? end; ``` It's this possible?. What is the best way to doit this?.