C++
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).
Exercise 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.
Show example solution
#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;
}
Test yourself
-
What is the first step in this project?
- Reading user input
- Adding error handling
- Setting up a loop
- Defining the Calculator class
Show answer
Defining the Calculator class — First we need to define the Calculator class skeleton.
-
Class definition
____ Calculator {
public:
double add(double a, double b);
};
Show answer
class Calculator {
public:
double add(double a, double b);
};
-
Match the project parts
- class Calculator
- Class skeleton
- add, subtract
- Add and subtract
- multiply, divide
- Multiply and divide
- if (b == 0)
- Zero check
Next lesson: Add and subtract