[fpc-pascal]Linked List/ pointers/ casting/ OOP Question

Michael.VanCanneyt at Wisa.be Michael.VanCanneyt at Wisa.be
Sat Jul 10 11:52:41 CEST 2004


On Fri, 9 Jul 2004, Ron Weidner wrote:

> > Note: I don't see the definition of PWidget in your
> > code peace. I assume 
> > it's a pointer to a record containing a string
> > member named meta. But in 
> > your procedure
> > 
> >  procedure AddWidget(PWidget:pointer);
> > 
> > you use the very same identifier, PWidget, for a
> > variable name. That's a 
> > bit confusing.
> 
> You are the 2nd person that I've talked to that seemed
> confused about this.  Since I'm very new to pascal
> programming, I'm concerned that I may have a bad
> design.  In an attempt to confirm a design problem I'm
> going to try to explain what I'm trying to do and ask
> for advice on a better way to do it.
> 
> Ok... Basically I have 3 objects that look like
> this...
> 
>               Widget
>  ---------------|----------
> |                          |
> Container Widget    Entity Widget
> 
> One of the defining differances between an Entity
> Widget and a Container widget is that a Container
> Widget can contain other widgets.  (both other
> container widgets and entity widgets).  So I needed to
> create a dynamic list (linked list) that could address
> either a container widget or an entity widget.  So I
> created TWidgetList with the field 'widget' being an
> untyped pointer.  Now that I have this list, I need to
> add addresses of _existing_ widgets to the list.  So,
> when I call the method...
> 
> procedure AddWidget(PWidget:pointer); 
> 
> I'm referring to a PWidget but I don't know of which
> type.  (container or entity) 

It should be of type Widget.

procedure AddWidget(AWidget : Widget);

> 
> During construction of an Entity or Container widget,
> the string meta is set to identify what type of widget
> it is. 

It is far easier:

  TWidget = Class (..)
  end;

  TEntityWidget = Class(TWidget)
  TContainerWidget = Class(TWidget)

I added the 'T' before the class name. It is good programming
practice to prepend type names with T, and pointers to types 
with P. It helps differentiating between types and variables 
of a type. 

> Now later, I can traverse the TWidgetList,
> read the meta string, cast the widget pointer to the
> right type and call the correct object methods. 
> (Render() in this case.)
> Is my code the long way around the barn or does it
> seem to make better sense explained?

It is, as you say, the long way around the barn (thanks for teaching me a
new expression :) ), and can be done much simpler, without the meta field.

when traversing the widget list you can simply do

  ...
  If Widget is TEntityWidget then
    TEntityWidget(Widget).Render // Or whatever. The point is the typecast.
  else if Widget is TContainerWidget then
    TContainerWidger(Widget).DoSomething;  // Here also, typecast.
  ...

Michael.




More information about the fpc-pascal mailing list