delphitcollectiontcollectionitem

how to change ItemClass of a class inherited from TCollection


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.


Solution

  • 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.