Simple Class Addition ( Add Two Integers ) Example Program In C++


Class and Object Definition

  • A class is a blueprint, or prototype which defines and describes the member attributes and member functions.
  • Objects are the instances of a class. Simply speaking, it may be defined as a variable of user-defined datatype classes. Through an object or instance, all member variables and member functions of classes can be accessed.

For a better understanding,

Class Syntax

class Classname {
    access_specifier:
    member_varibales;
    member_functions;
}object1, object2;

Simple Class Addition: Add Two Integers Example Program

/*  Simple Class Addition: Add Two Integers Example Program In C++
    Understanding Class                             */

// Header Files
#include <iostream>
#include<conio.h>

using namespace std;

// Addition Class Declaration
class AdditionClass {
private://Access - Specifier
   //Member Variable Declaration
   int num1, num2, result;

public://Access - Specifier
   //Member Functions read(),sum() and print() Declaration

   void read() {
      //Get Input Values For Object Variables using cin
      cout << "Enter Number 1 :";
      cin >> num1;

      cout << "Enter Number 2 :";
      cin >> num2;
   }

   void sum() {
      // Calculating sum value and assign in 'result'
      result = num1 + num2;
   }

   void print() {
      //Print the Output using cout
      cout << "Result :" << num1 << " + " << num1 << " = " << result << endl;
   }
};

int main() {
   // Object Creation For Class
   AdditionClass obj1, obj2;

   cout << "Simple Class Addition : Add Two Integers In C++\n";

   cout << "\nAdditionClass : obj1 Usage" << endl;
   obj1.read();
   obj1.sum();
   obj1.print();

   cout << "\nAdditionClass : obj2 Usage" << endl;
   obj2.read();
   obj2.sum();
   obj2.print();

   getch();
   return 0;
}

Sample Output

Simple Class Addition: Add Two Integers In C++

AdditionClass : obj1 Usage
Enter Number 1 :100
Enter Number 2 :200
Result :100 + 100 = 300

AdditionClass : obj2 Usage
Enter Number 1 :700
Enter Number 2 :900
Result :700 + 700 = 1600