Re: inheritance, list of objects, polymorphism
On Dec 17, 8:35 pm, "io_x" <a...@b.c.invalid> wrote:
"barbaros" <barba...@ptmat.fc.ul.pt> ha scritto nel messaggionews:f2890a48-ed1d-4451-86e6-12c5fb13ccc5@a21g2000yqc.googlegroups.com...
i not understand much but this seems ok
No it's not. Not from a design point, anyway, and it doesn't begin to
fulfill the requirements.
What he basically needs is something along the lines of:
// Interface...
class Expression
{
Expression( Expression const& );
Expression& operator=( Expression const& );
public:
virtual ~Expression() {}
virtual double value() const = 0;
// other functions...?
};
class OneOperandExpression : public Expression
{
protected:
OneOperandExpression( Expression const* op )
: m_op( op )
{
}
Expression const* m_op;
public:
virtual ~OneOperandExpression() { delete m_op; }
};
class TwoOperandExpression : public Expression
{
protected:
TwoOperandExpression( Expression const* lhs, Expression const*
rhs )
: m_lhs( lhs )
, m_rhs( rhs )
{
}
Expression* m_lhs;
Expression* m_rhs;
public:
virtual ~TwoOperandExpression() { delete m_lhs; delete
m_rhs; }
};
class ConstantExpression : public Expression
{
double m_value;
public:
ConstantExpression( double value )
: m_value( value )
{
}
virtual double value() const
{
return m_value;
}
};
class NegExpression : public OneOperandExpression
{
public:
NegExpression( Expression const* op )
: OneOperandExpression( op )
{
}
virtual double value() const
{
return - m_op->value();
}
};
class AddExpression : public TwoOperandExpression
{
public:
AddExpression( Expression const* lhs, Expression const* rhs )
: TwoOperandExpression( lhs, rhs )
{
}
virtual double value() const
{
return lhs->value() + rhs->value();
}
};
Systematic use of boost::shared_ptr< Expression const > in place of
Expression const* would simplify things somewhat. Providing static
factory functions for each type, with the actual constructors private,
would ensure that all instances are dynamically allocated (and
immediately put under control of a shared_ptr, if shared_ptr is being
used). Using some sort of "designated" memory management can make
things significantly safer and faster, at the cost of some additional
complexity, including at the client level.
--
James Kanze