A Simple Calculator

January 1, 2020

I’ve gotten a few messages from C++ Crash Course readers asking for hints on the Exercises from Chapter 2, Types. In this short blog post, I’ll give you a boost!

(Spoiler here)

2-1 - Create an Operation enum class

2-1. Create an enum class Operation that has values Add, Subtract, Multiply, and Divide.

This exercise is fairly straightforward. From p. 49, you know how to declare these:

enum class Operation {
  // Put the valid values here!

2-2 - Create a Calculator class

2-2. Create a struct Calculator. It should have a single constructor that takes an Operation.

From p. 58, you know that you can declare a class with a constructor using a special method that shares the same name as the class and has no return type.

Here’s a hint:

struct Calculator {
  Calculator( /* Put the Operation argument here! */ ) {
    // Save the operation into the op member
  Operation op;

2-3 - Create a calculate method

2-3. Create a method on Calculator called int calculate(int a, int b). Upon invocation, this method should perform addition, subtraction, multiplication, or division based on its constructor argument and return the result.

p. 55 shows you how to add methods to a class. Within your calculate method, you can use a switch statement from p. 50 to perform the appropriate operation.

struct Calculator {
  // --snip--
  int calculate(int a, int b) {
    switch (op) {
      // Put the appropriate cases and operations here

2-4 Experiment!

2-4. Experiment with different means of initializing Calculator instances.

You can use your Calculator by passing different Operation values on construction. Then, invoke calculate and print the result.

int main() {
  Calculator add_calc(Operation::Add);
  printf("1 + 2 = %d\n", add_calc.calculate(1, 2));

Share and Enjoy

That’s it! I hope you enjoyed Chapter 2. There’s a lot more in store.