[fpc-pascal]Polymorphism of class field

Michael Van Canneyt michael.vancanneyt at wisa.be
Thu Aug 30 09:10:13 CEST 2001


On Wed, 29 Aug 2001, Patrick O'Leary wrote:

>
>
> I am having trouble with polymorphism in a unit I am working on.
>
> I have several classes defined as follows:
>
> type
>
>          TStackElem = class
>                  public
>                  constructor Init; virtual;
>                  destructor Done; virtual;
>                  Prolog : TRPLObjectType;
>                  Next : TStackElem;
>                  function Decomp : string; virtual; abstract;
>          end;
>
>          TStackReal = class(TStackElem)
>                  public
>                  constructor Init; override;
>                  Data : real;
>                  function Decomp : string; override;
>          end;
>
>          TStackCharString = class(TStackElem)
>                  public
>                  constructor Init; override;
>                  Data : string;
>                  function Decomp : string; override;
>          end;
>
> Note the Data field: it is not present in the parent class, and is defined
> as two different types in the child class.
>
> I also have defined the function:
>
> function Parse(Command : string) : TStackElem;
> begin
>          // Decide type of data based on Command
>          // Define Parse as being TStackReal or TStackCharString (running
> Parse := TStackReal.Init, etc.)
>          // Put properly parsed data in Data field
> end;
>
> I haven't written the internal part of this function this time, but in
> previous attempts, the part of this function that 'Puts properly parsed data
> in Data field' of the TStackElem causes a compilation error, due to the Data
> field not being defined for TStackElem. In the absence of a Variant type
> (with which I would define Data : variant in TStackElem), how should I
> implement
> the above function?

You can't. You'll either have to typecast to the actual type, or provide
abstract functions as SetDataFromReal() and SetDataFromString() in TStackElem
which are implemented in the descendents, and which set the data, based on
the actual type.

In TStackReal the SetDataFromString can do 2 things: Attempt to convert the string
to a real (which would be my choice), or raise an error saying that the data type
is not supported.

TStackCharString can do the opposite with SetDataFromReal.

Michael.





More information about the fpc-pascal mailing list