1

I have a class which inherited from TCollection (lets call it "TMyCollection") and I have to inherit a new class from it (lets call it "TMyItems")

Usually we pass the ItemClass type in the constructor of the TCollection but in my case the constructor of TMyCollection is overrided with new constructor which doesn't take ItemClass and it does only take the Owner.

I need to know how to change the ItemClass in "TMyItems" if the inherited constructor doesn't accept ItemClass parameter.

Regards.

user1512094
  • 611
  • 2
  • 10
  • 23

1 Answers1

1

You can still call the inherited TCollection.Create from within a subclass, even if it doesn't have the same signature:

  TMyCollectionItem = class(TCollectionItem)
  private
    FIntProp: Integer;
    procedure SetIntProp(const Value: Integer);
  public
    property IntProp: Integer read FIntProp write SetIntProp;
  end;

  TMyCollection = class(TCollection)
  public
    constructor Create(AOwner: TComponent);virtual;
  end;

{ TMyCollection }

constructor TMyCollection.Create(AOwner: TComponent);
begin
  inherited Create(TMyCollectionItem); // call inherited constructor
end;

EDIT :

As per the original poster's comments, a "trick" is to mark the new constructor as overloaded. As it is an overload, it doesn't hide access to the TCollection constructor.

  TMyCollection = class(TCollection)
  public
    constructor Create(AOwner: TComponent);overload;  virtual;
  end;

  TMyItem = class(TCollectionItem)
  private
    FInt: Integer;
  public
    property Int: Integer read FInt;
  end;

  TMyItems = class(TMyCollection)
  public
    constructor Create(AOwner: TComponent);override;
  end;

implementation

{ TMyCollection }

constructor TMyCollection.Create(AOwner: TComponent);
begin
  inherited Create(TCollectionItem);

end;

{ TMyItems }

constructor TMyItems.Create(AOwner: TComponent);
begin
  inherited Create(TMyItem);
  inherited Create(AOwner); // odd, but valid
end;

end.
Gerry Coll
  • 5,867
  • 1
  • 27
  • 36
  • The problem is that I have 2 levels of inheritance the code is like the following : TMyCollection = class(TCollection).... the constructor of TMyCollection is constructor Create(AOwner: TComponent); TMyItems = class(TMyCollection) the constructor of TMyItems : constructor Create(AOwner: TComponent); when trying to call inherited constructor in TMyItems it will call the constructor of TMyCollection which is not what I want because I have new a ItemClass and it must be passed to the collection... – user1512094 Jul 11 '12 at 09:29
  • the New ItemClass is also inherited from TMyCollectionItem so it will have all properties and events TMyCollectionItem – user1512094 Jul 11 '12 at 09:34