Binary + Operator Overloading In CPP
Introduction
The provided C++ program showcases the implementation of operator overloading, specifically the binary + operator, within a class called Number. Operator overloading enables the user-defined types to work with standard operators, making the code more expressive and intuitive.
Key Concepts
1) Operator Overloading:
- Allows custom behavior for operators in user-defined classes.
- In this example, the + operator is overloaded to perform addition for instances of the Number class.
2) Class and Object:
- The Number class encapsulates data members a and b and methods for setting data (getdata) and displaying data (display).
3) Encapsulation:
- Data members of the class are private, and access to them is controlled by public member functions.
Code Structure
Class Definition (Number):
- Data members: a and b.
- Public member functions: getdata, display, and operator +.
Main Function:
- Creates instances of the Number class (n, n3, and obj).
- Calls member functions to set and display data.
- Demonstrates the use of the overloaded + operator.
Code Example
C++
#include<iostream> using namespace std; class Number
{
int a, b;
public:
void getdata(int x, int y)
{
a = x;
b = y;
}
void display()
{
cout << "A = " << a << endl;
cout << "B = " << b << endl;
}
Number operator +(Number n1)
{ Number n2; n2.a = a + n1.a; n2.b = b + n1.b; return n2; } }; int main()
{
Number n; n.getdata(10, 20); n.display(); Number n3; n3.getdata(20, 30); n3.display(); Number obj; obj = n + n3; // This is where the overloaded + operator is used. obj.display(); return 0; }
Code Explanation
- The Number class defines data members and functions for data manipulation.
- The + operator is overloaded to perform the addition of two Number objects.
- The main function demonstrates the creation of instances, data manipulation, and the use of the overloaded operator.
Code Output
A = 10
B = 20
A = 20
B = 30
A = 30
B = 50
Conclusion
This C++ program illustrates the implementation of operator overloading for the + operator within a class, showcasing how user-defined types can mimic the behavior of built-in types. Understanding operator overloading enhances code readability and allows for a more natural expression of mathematical operations in custom classes.