Home » C++ programs » C++ Most popular & searched programs

C++ program to add two integer numbers using class

In the last three programs we have discussed to find addition of two numbers using three different ways, if you didn't read them, please read them first. Here are the links of those programs:

  1. Addition of two integer numbers using normal way
  2. Addition of two integer numbers using user defined function
  3. Addition of two integer numbers using pointers

This program will find the addition/sum of two integer numbers using C++ class.

In this program, we are implementing a class Numbers that will read two integer numbers using readNumbers() member function, and return the sum of the numbers using calAddition() member function. There is a member function printNumbers() that will print the input values.

Program to add two numbers using class in C++



#include <iostream>
using namespace std;

//class definition
class Numbers
{
	private:
		int a;
		int b;
	public:
		//member function declaration
		void readNumbers(void);
		void printNumbers(void);
		int calAddition(void);
};

//member function definitions
void Numbers::readNumbers(void)
{
	cout<<"Enter first number: ";
	cin>>a;
	cout<<"Enter second number: ";
	cin>>b;	
}

void Numbers::printNumbers(void)
{
	cout<<"a= "<<a<<",b= "<<b<<endl;
}

int Numbers::calAddition(void)
{
	return (a+b);
}

//main function
int main()
{
	//declaring object
	Numbers num;
	int add; //variable to store addition
	//take input
	num.readNumbers();
	//find addition
	add=num.calAddition();
	
	//print numbers
	num.printNumbers();
	//print addition
	cout<<"Addition/sum= "<<add<<endl;
	
	return 0;	
}

Output

Enter first number: 100 
Enter second number: 200
a= 100,b= 200 
Addition/sum= 300





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.