Let us suppose I want to model propositional formulae.
A formula is either a proposition, the negation of a formula, the conjunction of two formulae or the disjunction of two formulae.
Additional, formulae are associated with a truth value (i.e. true or false).
Ideally, I would want to model it like that:
class Formula { // abstract class
protected:
bool value;
public:
~Formula() = 0;
};
class Proposition : public Formula {
private:
string name;
public:
Proposition(string s, bool b) : value(b), name(s) {}
};
class Negation : public Formula {
private:
Formula* f;
public:
Negation(Formula* nested) : value(!nested->value), f(nested) {}
};
class Conjunction : public Formula {
private:
Formula* l;
Formula* r;
public:
Conjunction(Formula* f1, Formula* f2) : value(f1->value && f2->value), l(f1), r(f2) {}
};
// Disjunction similar to Conjunction
However, I cannot access the value
attribute of nested
, f1
and f2
(see https://stackoverflow.com/a/12271018/3923424 e.g.)
To overcome that, I added a public function get_value()
, but I do not find it very elegant.
I also want to avoid making value
public, as other classes should not be able to modify this attribute.
Finally, I could make all the derived classes friends of Formula
. But I am not entirely convinced that this is the best and/or simplest solution.
Is there an elegant way to solve this problem?
Bonus question: what if I want value
to be only accessible by the derived classes?