Build a calculator with C++

Add a Calculator Class

It’s time to add some math logic.

1. Go to the Project menu, and choose Add Class. Under Class Name, write “Calculator”. Click OK. This will add two new files to your project. To save all your changed files at once, press Ctrl + Shift + S. This is known as Save All, and the button for it can also be found beside the Save button. In general, it’s good practice to do Save All frequently, so you don’t miss any files when you save. Create a class A class is like a blueprint for an object that does something. In this case, we are defining a calculator and how it should work. The Add Class wizard you used above has created .h and .cpp files with the same name as the class. You can see a full list of your project files in the Solution Explorer window (visible on the side of the IDE). If the window isn’t visible, you can open it by going to the View menu and choosing Solution Explorer.
Solution Explorer
You should now have three tabs open in the editor: CalculatorTutorial.cpp, Calculator.h, and Calculator.cpp. If you accidentally close one of them, you can re-open it by double clicking it in the Solution Explorer.

2. In Calculator.h, remove the Calculator(); and ~Calculator(); lines that were generated - you won’t need them here. Then, add the following line of code so the file now looks like this:

#pragma once
class Calculator
    double Calculate(double x, char oper, double y);

Understanding the code

  • This line declares a new function called Calculate, which we’ll use to run math operations for addition, subtraction, multiplication, and division.
  • C++ code is organized into header (.h) files and source (.cpp) files. Several other file extensions are supported by various compilers, but these are the main ones to worry about. Functions and variables are normally declared upfront in header files, and implemented in source files. When you want to access code from another file, you can do add a #include "filename.h", where ‘filename’ is the name of the file.
  • The two lines you had to delete declare a constructor and destructor for the class. Some advanced code may implement these concepts, but they are beyond the scope of this tutorial.
  • It’s good practice to organize your code into different files based on what it does, so it’s easy to find the code you need later. In our case, we define the Calculator class separately from the file containing the main() function, but plan to still reference the calculator in main().

3. You’ll see a green squiggle appear under Calculate. This is because we haven’t defined the Calculate function in the .cpp file. Hover over the word, click the lightbulb that pops up, and choose Create definition of ‘Calculate’ in Calculator.cpp. A pop-up will appear, giving you a peek of the code change that was made in the other file. The code was added to Calculator.cpp.
Currently, it just returns 0.0. Let’s change that. Press Esc to close the pop-up.

4. Switch to the Calculator.cpp file in the editor window. Remove the Calculator() and ~Calculator() sections (as you did in the .h file) and add the following code to Calculate():

double Calculator::Calculate(double x, char oper, double y)
        case '+':
            return x + y;
        case '-':
            return x - y;
        case '*':
            return x * y;
        case '/':
            return x / y;
            return 0;

Understanding the code

  • The function Calculate consumes a number, an operator, and a second number, then performs the requested operation on the numbers.
  • The switch statement checks which operator was provided, and only executes the case corresponding to that operation. The default: case is a fallback in case the user types an operator that isn’t accepted, so the program doesn’t break. In general, it’s best to handle invalid user input in a more elegant way, but this is beyond the scope of this tutorial.
  • The double keyword denotes a type of number that supports decimals. This way, the calculator can handle both decimal math and integer math. The Calculate function is required to always return such a number due to the double at the very start of the code (denotes the function’s return type), which is why we’re returning 0 even in the default case.
  • The .h file declares the function header, so the compiler knows upfront what to expect from it. The .cpp file has all the implementation details of the function.

5. Now let’s update the main function in CalculatorTutorial.cpp:

#include "stdafx.h"
#include <iostream>
#include "Calculator.h"

using namespace std;  
int main()  
    double x = 0.0;
    double y = 0.0;
    double result = 0.0;
    char oper = '+';

    cout << "Calculator Console Application" << endl << endl;   
    cout << "Please enter the operation to perform. Format: a+b | a-b | a*b | a/b" 
         << endl;
    Calculator c;
    while (true)
        cin >> x >> oper >> y;
        result = c.Calculate(x, oper, y);
        cout << "Result is: " << result << endl;

    return 0;

Understanding the code

  • Since C++ programs always start at the main() function, we need to call our other code from there, so a #include statement is needed.
  • Some initial variables x, y, oper, and result are declared to store the first number, second number, operator, and final result, respectively. It is always good practice to give them some initial values to avoid undefined behavior, which is what is done here.
  • The Calculator c; line declares an object called ‘c’ of the Calculator class. The class itself is just a blueprint for how calculators work; the object is the specific calculator that will do the math.
  • The while (true) statement is a loop. The code inside the loop will continue to execute over and over again as long as the condition inside the () holds true. Since the condition is simply listed as true, it will always be true, so the loop runs forever. To close the program, the user will need to manually close the terminal window. Otherwise, the program will always wait for new input.
  • The cin keyword is used to accept input from the user. This input stream is smart enough to process a line of text provided via the console window and place it inside each of the variables listed, in order, assuming the user input matches the required specification. You can modify this line to accept different types of input, like more than two numbers for instance, though the Calculate() function would also need to be updated behind the scenes to handle this.
  • The c.Calculate(x, oper, y) calls the Calculate function defined earlier with the provided input. The function will then return a number that gets stored in result.
  • Lastly, result is printed to the user, so the user knows what the result of the calculation was.

6. Now it’s time to test the program again to make sure everything works properly. Hit Ctrl + F5, type “5 + 5”, and press Enter. Verify that the result is 10. FivePlusFive 7. Close the terminal window.

I ran into an issue Continue tutorial