[fpc-pascal] Heterogenous list of objects

Damien Gerard milipili at shikami.org
Tue Jan 22 12:09:20 CET 2008


On Jan 22, 2008, at 11:22 AM, g.marcou at chimie.u-strasbg.fr wrote:

> Hi,
>
> I'd like to manage a list of heterogenous objects. For instance, I  
> have a list of objects to buy in store: cheeses (of class TCheese),  
> soaps (of class TSoap), flowers (of class TFlower), etc...
>
> I thought to gather pointers to different objects of these classes  
> in a TList. But, when it comes to manipulate or destroy these items,  
> I am in trouble: I have lost the information about the precise type  
> of the object the pointer points to.
>
> Does somebody have an idea?
>

Like this :
(I can make a complete example if needed)


type
   TNodeAbstract = class
      procedure print;virtual;abstract;
   end;

   TNodeFoo = class(TNodeAbstract)
      procedure print;override;
      procedure SpecificMethodeForFoo;
   end;


...

var objs: TObjectList;
objs := TObjectList.Create(True);
objs.Add(TNodeFoo.Create);

...


var o : TNodeAbstract;
for i := 0 to objs.Count - 1 do begin
    o := TNodeAbstract(Objs[i]);
    if (o is TNodeFoo) then
       (o as TNodeFoo).SpecificMethodeForFoo;
    o.Print;
end;



> Thanks in advance,
> Gilles Marcou
>
>
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal



--
Damien Gerard
milipili at shikami.org

Le temps n'a pas d'importance. Seul le code est important
    -- (f00ty)







More information about the fpc-pascal mailing list