CS 70

Real-World Example: Representing Expressions

  • Goat speaking

    Meh. Whenever object-oriented stuff comes up, people are always giving these forced examples, like shapes with circles and squares, or different kinds of animals. I still don't get what people actually use this stuff for.

  • LHS Cow speaking

    A really good example of a class hierarchy is often found in user interfaces—you have Control as a base class, and then Button and Slider would be derived from that, and so on. Control might provide some common functions, like drawing or being clicked on, and then the more specific classes implement their own additional functionality.

  • Goat speaking

    Okay, but what else? Is that it?

  • LHS Cow speaking

    Well, our Clang compiler is written in C++. When it's compiling your code, it represents your entire program as a class hierarchy—the output code is also represented that way.

  • Dog speaking

    Cool! But, uh, I have no idea how that would work.

  • Pig speaking

    Yes, tell us MORE!


We'll just look at a simple example—representing arithmetic expressions—but the ideas generalize. In the code linked below, we've made

  • An Expression abstract-base class, which supports an evaluate operation to produce the value of the expression.
  • Two concrete classes derived from that base class:
    • A Number class.
    • A BinaryExpression class that has two subexpressions and an operator.

Check out the code:

  • Goat speaking

    Meh, seems like an overcomplicated way to just do some simple math.

  • LHS Cow speaking

    Sure, if we just want to calculate a sum, we can fire up Python and type it in. But in this class, we like to know how stuff really works under the covers, and when you type an expression into Python, it's actually building an expression tree much like our example code does.

  • RHS Cow speaking

    And, yes, it's very basic. We deliberately used a simple example so you could see the class hierarchy and how it works without getting distracted by the other parts we'd need to make a more useful program.

  • LHS Cow speaking

    But with this code as a base, we can read code into expressions, process them, print them, and so on.

Here's a more developed version of the same code. Looking at this version is optional.

What do you think?

  • Goat speaking

    Will this be on the test?

  • LHS Cow speaking

    No. We're just trying to give a bigger sense of how class hierarchies can be applied. And this example is just one of numerous possibilities.

  • Duck speaking

    I feel kind of inspired. I could make my own programming language.

  • LHS Cow speaking

    And that's really the point of these examples—and CS 70—to both understand a bit about how these things work and recognize ways that you could use them.

(When logged in, completion status appears here.)