Not really.  If you have

type
  TBase = class(TObject);
  TFoo = class(TBase);
  TBar = class(TFoo);

then when you call the constructor you are specifying the class at that
point anyway - you don't need to provide it as a parameter.  Eg.

  TFoo.Create

is fine - passing the class as a parameter

  TFoo.Create(TFoo)

is redundant because we already know we're creating a TFoo.  The only case I
think of where the base class would care what type of class it is if it
needed to create a class of the same type of itself.  Here's one way to do
that:

function TBase.CreateAgain: TBase;
begin
  Result := ClassType.Create as TBase;
end;

then you could for example, have

var F1, F2: TFoo;

  F1 := TFoo.Create;
  F2 := F1.CreateAgain as TFoo; // Creates a TFoo

or

  F1 := TBar.Create;
  F2 := F1.CreateAgain as TFoo; // Creates a TBar

A more commonly used technique is to do the construction from outside the
class, eg. from within a class factory.  You can provide the class you want
created via a "class of" variable:

type
  TBaseClass = class of TBase;

var D, E: TFoo;
var B: TBaseClass;

  B := TFoo;
  D := B.Create; // Creates a TFoo
  B := TBar;
  E := B.Create; // Creates a TBar

As a final note, one place in the VCL where a class *is* passed to a
constructor is in the implementation of TCollection/TCollectionItem, because
when a TCollection descendant is created, it needs to know what type of
TCollectionItem descendant to create up front, for use for example when
calling the Add or Insert methods.  So TCollection.Create looks as follows:

type
  TCollectionItemClass = class of TCollectionItem;

constructor TCollection.Create(ItemClass: TCollectionItemClass);
begin
  FItemClass := ItemClass;
  ...
end;

This enables the TCollection to create instances of the class you provided
in the constructor, eg. in the Add method:

function TCollection.Add: TCollectionItem;
begin
  Result := FItemClass.Create(Self);
end;

HTH.

Cheers,
Carl

-----Original Message-----
From: Tony Sinclair [mailto:[EMAIL PROTECTED]]
Sent: Tuesday, 7 November 2000 9:46 AM
To: Multiple recipients of list delphi
Subject: [DUG]: Object Construction


Hi all,

Is it possible to have a constructor for the parent class that receives a
parameter which determines the type of child that is instantiated in it's
place?

Tony Sinclair
Holliday Group Limited
Christchurch
New Zealand

---------------------------------------------------------------------------
    New Zealand Delphi Users group - Delphi List - [EMAIL PROTECTED]
                  Website: http://www.delphi.org.nz
To UnSub, send email to: [EMAIL PROTECTED] 
with body of "unsubscribe delphi"
---------------------------------------------------------------------------
    New Zealand Delphi Users group - Delphi List - [EMAIL PROTECTED]
                  Website: http://www.delphi.org.nz
To UnSub, send email to: [EMAIL PROTECTED] 
with body of "unsubscribe delphi"

Reply via email to