CodeBlanks Logo Icon CodeBlanks

Project design

Design the structure of the calculator project and write the skeleton code.

Project: Calculator

In this 5-lesson project you will build a calculator. Each lesson adds one piece, and by the final lesson you will have a complete app.

You will use what you learned before:

  • defining a class with class
  • double variables and parameters
  • declaring and calling methods
  • writing output with std::cout

You will also learn a for loop, a switch menu and zero-division checking. Ready? Let us start.

Classes with class

A class groups data and the methods that operate on it. In the calculator, we will define the four operations as methods of a Calculator class.

The class syntax:

class Calculator {
public:
    double add(double a, double b) {
        return 0;
    }
};

The public: line marks the following methods as callable from outside. Each method returns a type (double) and takes parameters (a, b).

Practice Define the Calculator class

Define the Calculator class with empty bodies. Four methods (add, subtract, multiply, divide) each take two double parameters and return 0;. Place them under public:. The main already calls calc.add(3, 4); just defining the class is enough to compile.

Starter code

main.cpp
#include <iostream>

// Define the Calculator class here

int main() {
    Calculator calc;
    std::cout << calc.add(3, 4) << std::endl;
    return 0;
}

Sample solution

main.cpp
#include <iostream>

// Define the Calculator class here
class Calculator {
public:
    double add(double a, double b) { return 0; }
    double subtract(double a, double b) { return 0; }
    double multiply(double a, double b) { return 0; }
    double divide(double a, double b) { return 0; }
};

int main() {
    Calculator calc;
    std::cout << calc.add(3, 4) << std::endl;
    return 0;
}

Expected output

0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the first step in this project?

  • Reading user input
  • Adding error handling
  • Setting up a loop
  • Defining the Calculator class Correct answer

Explanation: First we need to define the Calculator class skeleton.

2 Class definition

Question
____ Calculator {
public:
    double add(double a, double b);
};
Answer
class Calculator {
public:
    double add(double a, double b);
};

Explanation: The class keyword defines a class.

3 Match the project parts

Term Meaning
class Calculator Class skeleton
add, subtract Add and subtract
multiply, divide Multiply and divide
if (b == 0) Zero check

All lessons in Beginner