Real-World Example: Representing Expressions
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.
A really good example of a class hierarchy is often found in user interfaces—you have
Control
as a base class, and thenButton
andSlider
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.Okay, but what else? Is that it?
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.
Cool! But, uh, I have no idea how that would work.
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 anevaluate
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.
- A
Check out the code:
Meh, seems like an overcomplicated way to just do some simple math.
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.
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.
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.
Will this be on the test?
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.
I feel kind of inspired. I could make my own programming language.
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.)