C++ Program To Find Sum Of Two Numbers Using Class And Object
Using classes and objects in C++ is a fundamental concept of Object-Oriented Programming (OOP) that allows you to bundle data and the functions that operate on that data into a single unit. In this article, you will learn how to use C++ classes and objects to find the sum of two numbers, demonstrating basic OOP principles.
Problem Statement
The challenge is to perform a simple arithmetic operation—adding two numbers—but specifically by leveraging C++ classes and objects instead of just a standalone function or direct arithmetic. This approach emphasizes encapsulation and object interaction, which are core to building more complex, modular applications. While a direct sum is trivial, implementing it with a class sets the foundation for more sophisticated data management and operations.
Example
Consider a scenario where you have two numbers, 10 and 20, and you want to find their sum using a class-based structure. The expected output would clearly state the sum, illustrating the successful operation of the class.
The sum of 10 and 20 is: 30
Background & Knowledge Prerequisites
To understand this article effectively, readers should be familiar with the following C++ concepts:
- Variables and Data Types: Basic understanding of integer types (
int) and variable declaration. - Functions: How to define and call functions.
- Basic I/O: Using
coutfor output andcinfor input. - Classes and Objects: Fundamental understanding of what a class is (a blueprint) and what an object is (an instance of a class).
- Access Specifiers: Knowledge of
publicandprivatekeywords to control member visibility. - Constructors: How special methods are used for object initialization.
Use Cases or Case Studies
Using classes to encapsulate data and operations, even for a simple sum, extends to many real-world applications:
- Calculator Applications: Each operation (addition, subtraction, multiplication) could be a method within a
Calculatorclass, handling various number inputs. - Financial Systems: An
Accountclass might have methods todeposit(add funds) orwithdraw(subtract funds), where the balance is a private data member. - Inventory Management: A
Productclass could manage quantity, with methods toaddStockorremoveStock, affecting the total count. - Game Development: A
Playerclass might track scores or health points, with methods toaddScoreorhealPlayer. - Sensor Data Processing: A
SensorDataclass could collect multiple readings and have methods to calculate aggregates liketotalSumoraverageof the readings.
Solution Approaches
Here, we explore various ways to find the sum of two numbers using C++ classes and objects, each demonstrating a different aspect of class functionality.
1. Basic Class Approach with Private Members
This approach defines a class with private data members to store the numbers and public methods to set these numbers, calculate their sum, and display the result. This exemplifies encapsulation where data is hidden and accessed only through public methods.
- One-line summary: Encapsulates two numbers and provides public methods to set them, calculate their sum, and display the result.
// Sum of Two Numbers using Basic Class
#include <iostream>
using namespace std;
// Define a class named 'Adder'
class Adder {
private:
int num1; // Private data member to store the first number
int num2; // Private data member to store the second number
public:
// Method to set the two numbers
void setNumbers(int a, int b) {
num1 = a;
num2 = b;
}
// Method to calculate the sum
int calculateSum() {
return num1 + num2;
}
// Method to display the sum
void displaySum() {
cout << "The sum of " << num1 << " and " << num2 << " is: " << calculateSum() << endl;
}
};
int main() {
// Step 1: Create an object (instance) of the 'Adder' class
Adder myAdder;
// Step 2: Set the numbers using the 'setNumbers' method
myAdder.setNumbers(10, 20);
// Step 3: Call the 'displaySum' method to show the result
myAdder.displaySum();
return 0;
}
- Sample Output:
The sum of 10 and 20 is: 30
- Stepwise Explanation:
- Class Definition: The
Adderclass is defined with twoprivateinteger members,num1andnum2, ensuring they can only be accessed or modified via the class's public methods. - Public Methods:
-
setNumbers(int a, int b): A method that takes two integers as arguments and assigns them tonum1andnum2.
-
calculateSum(): A method that returns the sum of num1 and num2.displaySum(): A method that prints a formatted string including num1, num2, and their sum by calling calculateSum().- Object Creation: In
main(), an object namedmyAdderis created from theAdderclass. - Method Calls: The
setNumbers()method is called onmyAdderto initialize the numbers. Then,displaySum()is called to compute and print the sum.
2. Using a Constructor for Initialization
Constructors are special member functions that are automatically called when an object is created. They are often used to initialize the object's data members.
- One-line summary: Initializes the numbers directly when an object is created, simplifying object setup and ensuring data integrity from the start.
// Sum of Two Numbers using Class with Constructor
#include <iostream>
using namespace std;
// Define a class named 'AdderWithConstructor'
class AdderWithConstructor {
private:
int num1;
int num2;
public:
// Constructor to initialize num1 and num2
AdderWithConstructor(int a, int b) {
num1 = a;
num2 = b;
cout << "Object created and numbers initialized." << endl;
}
// Method to calculate the sum
int calculateSum() {
return num1 + num2;
}
// Method to display the sum
void displaySum() {
cout << "The sum of " << num1 << " and " << num2 << " is: " << calculateSum() << endl;
}
};
int main() {
// Step 1: Create an object of 'AdderWithConstructor', passing numbers directly to the constructor
AdderWithConstructor anotherAdder(15, 25);
// Step 2: Call the 'displaySum' method to show the result
anotherAdder.displaySum();
return 0;
}
- Sample Output:
Object created and numbers initialized.
The sum of 15 and 25 is: 40
- Stepwise Explanation:
- Constructor Definition: The
AdderWithConstructorclass has a public constructorAdderWithConstructor(int a, int b). This constructor takes two integers and assigns them tonum1andnum2upon object creation. - Object Creation and Initialization: In
main(), whenAdderWithConstructor anotherAdder(15, 25);is executed, the constructor is automatically called with 15 and 25, initializingnum1andnum2immediately. - Method Call: The
displaySum()method is then called to present the pre-initialized numbers and their sum.
3. Using Member Functions to Get Input from User
This approach demonstrates how to make the class interactive by having a member function prompt the user for input and store it directly into the object's data members.
- One-line summary: A class method prompts the user to input numbers, making the object dynamic and responsive to user interaction.
// Sum of Two Numbers using Class with User Input
#include <iostream>
using namespace std;
// Define a class named 'InteractiveAdder'
class InteractiveAdder {
private:
int num1;
int num2;
public:
// Method to get numbers from the user
void getNumbersFromUser() {
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
}
// Method to calculate the sum
int calculateSum() {
return num1 + num2;
}
// Method to display the sum
void displaySum() {
cout << "The sum of " << num1 << " and " << num2 << " is: " << calculateSum() << endl;
}
};
int main() {
// Step 1: Create an object of the 'InteractiveAdder' class
InteractiveAdder userAdder;
// Step 2: Call the 'getNumbersFromUser' method to prompt for input
userAdder.getNumbersFromUser();
// Step 3: Call the 'displaySum' method to show the result
userAdder.displaySum();
return 0;
}
- Sample Output:
Enter first number: 5
Enter second number: 7
The sum of 5 and 7 is: 12
- Stepwise Explanation:
getNumbersFromUser()Method: TheInteractiveAdderclass includes a methodgetNumbersFromUser()which usescoutto prompt the user andcinto read the two numbers into thenum1andnum2members.- Object Creation: In
main(), anInteractiveAdderobjectuserAdderis created. - User Interaction: The
getNumbersFromUser()method is called onuserAdder, pausing the program to wait for user input. - Display Result: After the numbers are set by the user,
displaySum()is called to compute and show the sum.
Conclusion
By implementing the simple task of summing two numbers using classes and objects in C++, you have explored fundamental Object-Oriented Programming concepts. These examples highlight how classes encapsulate data and behavior, making code more organized, reusable, and maintainable. Whether through direct method calls, constructors, or user interaction, the class-based approach provides a structured way to handle data and operations.
Summary
- Classes and Objects: Classes serve as blueprints for creating objects, which are instances containing data (members) and functions (methods) that operate on that data.
- Encapsulation: Private data members (
num1,num2) protect the internal state of an object, which can only be modified or accessed through public methods (setNumbers,calculateSum,displaySum). - Constructors: Special methods automatically invoked during object creation, ideal for initializing object state immediately.
- Methods for Interaction: Member functions can be designed to handle user input (
getNumbersFromUser), perform calculations (calculateSum), and present results (displaySum). - Modularity and Reusability: Using classes enhances code organization, allowing for the creation of self-contained, reusable components for various tasks.