Re: inheritance, list of objects, polymorphism
On 15 d=E9c, 11:26, barbaros <barba...@ptmat.fc.ul.pt> wrote:
I need help with an inheritance issue. I am implementing a sort of
symbolic calculus code. By the way, is the site www.ginac.de closed ?
No
Back to my code. I have a base class "Expression" and derived classes
"ExpressionSum", "ExpressionProduct", "ExpressionPower" and so on. For
instance, xy+yz+z is an ExpressionSum of two ExpressionProduct and an
Expression. The class ExpressionSum is implemented as a list of terms
to sum up. These terms should be any other Expressions (Products,
Powers, or mere Expressions). The problem is, when I call
ExpressionSum::add(expr), expr being an ExpressionProduct, it looks
like expr is first converted to a mere Expression and then added to
the list.
Yes, you stores Expression values.
You should store Expression pointers which raises the problem of deep
copy. It is usually solved by implementing a 'virtual Expression* clone
()' operation.
Another alternative is to use the Envelope/Letter idiom.
This is different from what I want. I want a list of
Expressions, some of which should behave like Products, other like
Powers, etc.
I hope I made myself clear.
Yes
I include below a small piece of code.
[snip]
class Expression {
[snip]
class ExpressionProduct : public Expression {
[snip]
class ExpressionSum : public Expression {
public:
list<Expression> terms;
Here you have slicing of your objects.
If you make Expression virtual pure, you won't be able to compile your
code.
ExpressionSum ()
{cout << "constructor ExpressionSum, no arguments" << endl;}
void add (Expression &m)
{ cout << "adding" << endl; terms.push_back(m); }
string name()
{ cout << "method ExpressionSum::name"<< endl;
list<Expression>::iterator i=terms.begin();
if (i==terms.end()) return "0";
string n=i->name();
i++ ;
for (;i!=terms.end();i++)
n = n + '+' + i->name();
return n; }
};
int main () {
Expression x("x"), y("y"), z("z");
ExpressionProduct xy(x,y), yz(y,z);
cout << xy.name() << endl;
ExpressionSum p;
p.add(xy); p.add(yz); p.add(z);
cout << p.name() << endl;
}
--
Michael