In this article, we will learn how to add two numbers by using the classes. We will define a class that will have functions to take inputs from users,do additions, and display the results.
Explanation: C++ program to add two numbers using class
- Declare a class with two private members to save the user-provided numbers.
- Declare 2 public member functions in the class that will be used to take input from users and perform addition.
- Write the input and addition logic in the declared member functions.
- In the main() function, declare an object of the class.
- Using the class object call the member function to take input from the user.
- Using the class object call the member function to perform the addition on numbers.
- Display the results of addition.
#include <iostream>
using namespace std;
class AdditionClass
{
private:
int num1;
int num2;
public:
void InputNumbers();
int PerformAddition();
};
void AdditionClass::InputNumbers()
{
cout<<"Please enter First number: ";
cin>> num1;
cout<<"Please enter Second number: ";
cin>> num2;
}
int AdditionClass::PerformAddition()
{
int add = num1 + num2;
return add;
}
int main()
{
AdditionClass obj;
int sum = 0;
obj.InputNumbers();
sum = obj.PerformAddition();
cout<<"The Sum of the Given numbers "<< obj.num1<< " and" << obj.num2 << " is:"<< sum <<endl;
return 0;
}
Output
Please enter First number: 7
Please enter Second number: 4
The Sum of the Given numbers 7 and 4 is:11
- C++ Program to print alphabets triangle from A to E
- C++ Program to print diamond pattern
- C++ Program to print triangle pattern
- Program to print pi pattern in C++