Binary Operator Overloading
Binary Operator Overloading
Binary Operator Overloading
Example:
Assume that class Distance takes two member object i.e. feet and inches, create a
function by which Distance object should decrement the value of feet and inches by 1
(having single operand of Distance Type).
class Distance
{
public:
// Member Object
int feet, inch;
// Driver Code
int main()
{
// Declare and Initialize the constructor
Distance d1(8, 9);
Output:
In the above program, it shows that no argument is passed and no return_type value
is returned, because unary operator works on a single operand. (-) operator change
the functionality to its member function.
Let’s take the same example of class Distance, but this time, add two distance
objects.
class Distance
{
public:
// Member Object
int feet, inch;
// No Parameter Constructor
Distance()
{
this->feet = 0;
this->inch = 0;
}
// Driver Code
int main()
{
// Declaring and Initializing first object
Distance d1(8, 9);
Output:
Total Feet & Inches: 18'11
d3 = d1 + d2;
d1 calls the operator function of its class object and takes d2 as a parameter, by
which operator function return object and the result will reflect in the d3 object.