Putting It All Together
The main() function in Listing 8 begins by instantiating two objects of the VariableExpression class, called x and y. The objects x and y are simply Boolean values that can be either true or false.
Next, we create an instance of the OrExpression class. The constructor for the OrExpression instance is passed two parameters. These two parameters are two further derived objects of BooleanExpression—in this case, two instances of AndExpression. The constructor parameters to the first AndExpression object are new Constant(true) and x. (Listing 9 contains the Constant class.) The constructor parameters to the second AndExpression object are y and new NotExpression(x).
The class Constant is used to return a Boolean constant—either true or false. The class NotExpression is similar to OrExpression and AndExpression except that it takes just one parameter. The Evaluate() function for NotExpression simply negates that parameter and returns the result (that is, true becomes false and false becomes true).
Listing 8 The interpreter main() function.
int _tmain(int argc, _TCHAR* argv[]) { BooleanExpression* expression; Context context; VariableExpression* x = new VariableExpression("X"); VariableExpression* y = new VariableExpression("Y"); expression = new OrExpression( new AndExpression (new Constant(true), x), new AndExpression (y, new NotExpression(x))); context.AssignX(x, true); context.AssignY(y, false); bool result = expression->Evaluate(context); printf("Overall result is %d\n", result); return 0; }
Once the objects in Listing 8 have been instantiated, we update the context for x and y by calling context.AssignX() and context.AssignY(). Once the context is set up, we can call the Evaluate() function for our Boolean expression. Here’s the Boolean expression that we want to evaluate:
(true AND x) OR (y AND (NOT x))
where
x = true y = false
So we expect this to evaluate to true:
(true AND true) = true
Likewise,
(false AND false) = false
Then, taking (true OR false) = true.