Add two numbers using class in c++

Add two numbers using class in c++ is simple addition program which we are implementing using class in c++.

In this tutorial we will see what is class, How to add numbers using class , and  c++ program to add two numbers.

What is class ?

Class definition : Class is a user defined data type. It encloses data members and member functions.

By default all the members of the class are private.

How to add numbers using class

For this we create class addition in which we write functions which adds two numbers.

Algorithm to add two numbers using class in c++

  1. Start
  2. Write class and Define function which adds two numbers
  3. Write main function
  4. Take two number input
  5. Pass number and call function
  6. End

C++ addition program using class

123456789101112131415161718192021222324252627#include <iostream>using namespace std;class addition{       int a,b,sum;    public:        addition()        {                cout<<“\n Enter two values : “;                cin>>a>>b;        }        void add();   //member function};void addition :: add()  {        sum = a+b;        cout<<“\nAddition is = “<<sum;}int main(){        addition a1;   //object created        a1.add();        return 0;}

Output :

C++ addition program using class
C++ addition program using class

Explanation :

1. Execution starts with the main function.

2. Create a object of class addition. 

addition a1;   => object created and default constructor get executed

addition() {

cout<<“\n Enter two values : “;

cin>>a>>b;   => a = 12 , b= 12

}   => after constructor execution it returns to main function

3. Next we call function add

a1.add();   => function get call

void addition :: add() {  => function executed

sum = a+b;    => sum = 24

cout<<“\nAddition is = “<<sum;   => addition is = 24

}  => control returned to main function

4. End with the program.