I ran into the following problem and I don't really know what the best way is to approach this. I want to evaluate expression
objects that are constructed with a foo
object. The expression
class and its derived classes should be allowed to access private members of foo; but except from declaring all derived classes individually as friend I don't know how I could make this work - can I declare a virtual function a friend of foo
?
class foo{
public:
foo(int a, int b, int c) : a(a), b(b), c(c) {}
void addExpression(expression *e){exp.push_back(e);}
bool evaluateAll(){
for(expression* e : exp){
if(!e->evaluate())
return false;
}
return true;
}
private:
int a,b,c;
std::list<expression*> exp;
};
The expression
classes:
struct expression{
expression(foo *f) : f(f) {}
virtual bool evaluate() = 0;
private:
foo *f;
};
struct anExpression : public expression{
anExpression(foo *f) : expression(f) {}
bool evaluate(){
return f->a < f->b;
}
};
struct anotherExpression : public expression{
anotherExpression(foo *f) : expression(f) {}
bool evaluate(){
return f->a > f->b && f->a != f->c;
}
};
The main
function:
int main(int argc, char *argv[]){
foo f(3,2,1);
f.addExpression(new anExpression(&f));
f.addExpression(new anotherExpression(&f));
f.evaluateAll();
return 0;
}
This code doesn't work of course but I really don't want to add every derived class of expression
as a friend or make expression
inherit from foo
. Is there another solution?