C++ program to add two integer numbers using class

Given two integer numbers, we have to add them using class and object approach.
[Last updated : February 28, 2023]

Adding 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


Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.