Site icon T4Tutorials.com

Binary Operator Overloading C++ OOP

Let’s see the Binary Operator Overloading in C++ (OOP). Before this we have studied about unary operator overloading and assignment operator overloading.

Sum of two number – Binary Operator Overloading C++

#include <iostream>   
using namespace std; 
class Sum_T4Tutorials
{ 
public: 
int number; 
//constructor
Sum_T4Tutorials() 
{ 
number = 0; 
}   
//constructor
Sum_T4Tutorials(int n) 
{ 
number = n; 
}   
// Overloading (+) operator to perform 
// addition of two distance object 
//using binary operator Overloading
Sum_T4Tutorials operator+(Sum_T4Tutorials formal_parameter) // Call by value 
{ 
// Create an object to return 
Sum_T4Tutorials Object3;   
// Perform addition of number and inches 
Object3.number = number + formal_parameter.number; 
// Return the resulting object 
return Object3; 
} 
};  
int main() 
{ 
Sum_T4Tutorials Object1(3);   
Sum_T4Tutorials Object2(6); 
Sum_T4Tutorials Object3;   
//Use overloaded operator 
Object3 = Object1 + Object2; 
cout << "Sum of  Number & Inches is: " << Object3.number << endl; 
return 0; 
}

Output

Sum of Number & Inches is: 9

Addition of Feet and inches – Binary Operator Overloading C++

#include <iostream>   
using namespace std; 
class T4Tutorials_Height 
{ 
public: 
int feet, inches; 
//constrcutor
T4Tutorials_Height() 
{ 
//as we know that when we want to store sum of numbers, then 
//the variable is initialized with 0.
feet = 0; 
inches = 0; 
}   
//constrcutor
T4Tutorials_Height(int f, int i) 
{ 
feet = f; 
inches = i; 
}   
// Overloading of  (+) operator to perform addition 
// on two object using binary operator.
T4Tutorials_Height operator+(T4Tutorials_Height formal_parameter) // Call by value
{ 
// Create an object to return 
T4Tutorials_Height h3;   
// Perform addition of feet and incheses 
h3.feet = feet + formal_parameter.feet; 
h3.inches = inches + formal_parameter.inches; 
// Return the resulting object 
return h3; 
} 
};  
int main() 
{ 
T4Tutorials_Height h1(5, 2);   
T4Tutorials_Height h2(5, 4); 
T4Tutorials_Height h3;   
//Use overloaded operator 
h3 = h1 + h2; 
cout << "Sum of  Feet & Inches: " << h3.feet << "'" << h3.inches << endl; 
return 0; 
}

Output

Sum of Feet & Inches: 10, 6

Excercise

overloading binary minus operator in c++.
overloading binary plus operator in c++.
overloading binary multiplication operator in c++.
overloading binary division operator in c++.

More Operator Overloading Programs

Exit mobile version