`I want to make a calculator in C++ for addition, subtraction, multiplication and division using class template and in the main function, if the user entered integer it should call the class template with the integer type, if user enters a float then it should call the class template with the float type and so on for double and char.
Here is my code so far:
#include <iostream>
using namespace std;
template <typename T> //declare class template
class Calculator
{
public:
T number1;
T number2;
void accept()
{
}
public:
void addition() //for addition
{
T sum = number1 + number2;
cout<<"Sum of the two numbers= "<<sum<<"\n";
}
public:
void subtraction() //for subtraction
{
T diff = number1 - number2;
cout<<"Difference of the two numbers= "<<diff<<"\n";
}
public:
void multiplication() //for multiplication
{
T prod = number1 * number2;
cout<<"Product of the two numbers= "<<prod<<"\n";
}
public:
void division() //for division
{
T divi = number1 / number2;
try //exception handling for division by zero
{
if(number2 == 0)
{
throw number2; //throw exception if occured
}
cout<<"Division of the two numbers= "<<divi<<"\n"; //statement to print if exception doesnt occur
}
catch(float ex)
{
cout<<"Division by zero exception"; //statement to print if exception occurs
}
}
};
int main()
{
Calculator<float> obj1;
cout<<"*******************************************************************************************\n";
cout<<"Enter two variabes to perform mathametical operations: \n";
cout<<"*******************************************************************************************\n";
cout<<"Number 1: ";
cin>>obj1.number1; //accepting numbers from user
cout<<"\n";
cout<<"Number 2: "; //accepting numbers from user
cin>>obj1.number2;
cout<<"*******************************************************************************************\n";
cout<<"Choose an operation to perform with the numbers: \n";
cout<<"1. Addition\n";
cout<<"2. Subtraction\n";
cout<<"3. Multiplication\n";
cout<<"4. Division\n";
cout<<"*******************************************************************************************\n";
cout<<"Choice: ";
int c;
cin>>c;
cout<<"*******************************************************************************************\n";
cout<<"\n";
switch (c) //switch statement for menu
{
case 1: obj1.addition();
break;
case 2: obj1.subtraction();
break;
case 3: obj1.multiplication();
break;
case 4: obj1.division();
break;
default: cout<<"Invalid choice";
break;
}
return 0;
}
Here i called the template as float, but i want to call the template with the datatype based on the datatype entered by the user.`