Board index » delphi » Polymorphism - making an expression evaluator

Polymorphism - making an expression evaluator

Hi everyone!
I have a problem with polymorphism in Delphi.

I've got a class structure where the parent class is TExpObj.
From this class, several classes are inherited. The objects
are stored in a binary tree, and new instances of any class
can be inserted at any time.

The problem arises when I want to add new instances too the
tree. I'll use the base class TExpObj and a child class called
TExpLiteral for this example.
In C++ it would look like this (I'm translating a C++ expression
evaluator);

// Build is a function which takes a pointer to a TExpObj as its
// arguments.

Build(new TExpLiteral);

In Delphi, I've tried about a million different versions. One of
the few that has compiled is;

type
ptrTExpObj = ^TExpObj;

var
 ptrExpObj : ptrTExpObj;

New(ptrTExpLiteral(ptrExpObj));
ptrTExpLiteral(ptrExpObj).CreateValue(StrToFloat(sBuffer),self);
// Build is a procedure that takes a ptrTExpObj as its argument.
// <- this type of comment actually works with Delphi 2.0.
Build(ptrExpObj);

This code gives me a nice little 'Access Violation at...' message.
What the heck am I to do? If the info isn't enough, and you're still
interested I could mail you the source of both the C++ version and
my Delphi code.

I'll be willing to share the expression evaluator when it's properly
translated (if I ever get there). I found the source in C++ Journal.

-mattias, m...@dtek.se

--
---------------------------------------------------------------------------
t91ma...@und.ida.liu.se = Mattias Fagerlund, Linkoeping Sweden
One day I'll make me a real .signature, one day. You'll see.
---------------------------------------------------------------------------

 

Re:Polymorphism - making an expression evaluator


Quote
t91ma...@ida.liu.se (Mattias Fagerlund) wrote:

[...]

Quote
>In C++ it would look like this (I'm translating a C++ expression
>evaluator);

>// Build is a function which takes a pointer to a TExpObj as its
>// arguments.

>Build(new TExpLiteral);

>In Delphi, I've tried about a million different versions. [...]

When translating C, remember that Delphi doesn't typically use pointers for
Objects -- you just use the objects themselves, and it is always implied
that pointers are being passed around.

so declare Build:

function Build(Instance: TExpObj);

and call it thus:

Build(TExpLiteral.Create);

That should do the trick. (Note: this assumes the Create constructor is
parameterless -- you need to add whatever paramaters are needed to the
Create call, if necessary).

--
Brad Aisa <ba...@hookup.net>  web: http://www.hookup.net/~baisa/

1 Mises (M1.00) = 0.01 troy ounce gold; 1 Rand (1R) = 0.01 Mises

"The highest responsibility of philosophers is to serve as the
guardians and integrators of human knowledge."   -- Ayn Rand

Other Threads