ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Program to overload binary operator in c++

Updated on June 14, 2016

1. Binary Operator Overloading

The operator operates on the given operands. Say for example, 3 + 5 = 8. We all know that and in that example, 3 and 5 are considered as operands. The + is the operator which denotes the Addition operation on the operands 3 and 5. Eight is the result of the operation. As operator + operates on two operands, we call this + operator as a Binary operator.

The C++ programming language knows how to add to standard variables. But, how about the class objects? As you (i.e.) the user define the class, the language does not know how to add the two class objects. In that case, we should provide additional responsibility to the operator + to tell two class objects. In this hub, I will explain how do we overload the binary operator +.

2. The DivBy5 class

Have a look at the below-shown class diagram for the DivBy5 class:

Source

From the above diagram, you may realize what this class object will do. Now, the plus operator supported by the C++ language does not know how to add the two instances from the DivBy5 class. Say for Example, when we pass 7 to the constructor of this DivBy5 class, the members are initialized as shown below:

Source

Now if we want to add two instances of the same above-specified object, we know that only the member m_therNumber should be added and other members should be calculated. OK, let us see how can we overload the plus operator so that the statement Obj1 + Obj2 is valid when both the objects are instances of DivBy5 class.

At present the DivBy5 class looks like the below one:

class DivBy5
{
public:
    //Sample 01: It acts as Default Constructor as well as 
    // Conversion constructor.
    DivBy5(int number = 0)
    {
        m_theNumber = number;
        m_quotient = m_theNumber/5;
        m_reminder = m_theNumber%5;
    }

    //Sample 02: Print the Reminder and divident
    void print()
    {
        cout<<"Quotient ="<<m_quotient<<endl;
        cout<<"Reminder ="<<m_reminder<<endl;
    }

private:
    int m_quotient;
    int m_reminder;
    int m_theNumber;
};

Explanation

Snippet 01: Acts as default constructor as well as a constructor with a single argument. Note that as this constructor accepts single parameter as the integer the statement “DivBy5 = 7;” is possible as it invokes the constructor by passing the value 7 to it. The constructor fills all the members and I believe the code is easily understandable.

Snippet 02: Perform the printing of the constructed results. It shows the result of the division by five for the passed-in number.

4. Binary operator overloading in c++ using member function

The above class does not know how to add two instances. Look at the below snippet:

DivBy5 obj1(17);

DivBy5 obj2(22);

DivBy5 Obj3 = obj1 + obj2;

The third statement will give the compiler error as it does not know how to add obj1 and obj2 using the operator +.

The below code is added to the class DivBy5 to overload the plus operator so that it know how to add two DivBy5 instances. Code is below:

//Sample 03: OverLoading Operator +
DivBy5 operator+(DivBy5 obj2nd)
{
    return m_theNumber + obj2nd.m_theNumber;
}

In this snippet, the operator+() is invoked the first operand and the second operand is passed as the parameter to the overloaded operator function. Note how do we add the two numbers and return the result. It is bit tricky. The return type expected is DivBy5 and what we return is the result of integer addition. The return result will invoke the constructor with a single integer as an argument. The complete class with the above overload is shown below:

// TestIt.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;

//=========================================================
//Example: Overloaded + Operator as class member function
//=========================================================

class DivBy5
{
public:
    //Sample 01: It acts as Default Constructor as well as 
    // Conversion constructor.
    DivBy5(int number = 0)
    {
        m_theNumber = number;
        m_quotient = m_theNumber/5;
        m_reminder = m_theNumber%5;
    }

    //Sample 02: Print the Reminder and divident
    void print()
    {
        cout<<"Quotient ="<<m_quotient<<endl;
        cout<<"Reminder ="<<m_reminder<<endl;
    }

	//Sample 03: OverLoading Operator +
	DivBy5 operator+(DivBy5 obj2nd)
	{
		return m_theNumber + obj2nd.m_theNumber;
	}

private:
    int m_quotient;
    int m_reminder;
    int m_theNumber;
};

void main()
{
    //Usage 01: Construct 2 objects
    DivBy5 obj1(17);
    DivBy5 obj2(22);
    cout<<"Object 1"<<endl;
    obj1.print();
    cout<<"Object 2"<<endl;
    obj2.print();

    //Usage 02: Use the + Operator
    DivBy5 Obj3 = obj1 + obj2;
    cout<<"Object 3"<<endl;
    Obj3.print();

    //Usage 03: Use the + Operator with Const
    DivBy5 Obj4 = obj1 + 3;
    cout<<"Object 4"<<endl;
    Obj4.print();
}

Explanation


Usage 01: We create two objects obj1 and obj2 and print the objects after the creation. The print actually gives the result of the 17/5 and 22/5.

Usage 02: Here we perform the addition of two objects using our overloaded + operator. The overloaded + operator operates on two objects obj1 and obj2 and returns the result as third object obj3. Note that the Obj1 object calls the operator+() by passing the obj2 as a parameter. Keep this in mind and look at the plus operator implementation. The m_theNumber within the function refers the first operand of the plus operator and in our case, it is the member of obj1. Also, note that the second object's parameter is referred as obj2nd.m_theNumber as it is passed as a parameter. The added value 39 in is returned back and as we have a conversion constructor we get the result back as the object obj3.

Usage 03: Here we are trying to add the obj1 with the integer value of 3. The value three invokes the conversion constructor and passed as a parameter to the operator+(). The return value is stored in the obj4. As told in the code snippet for “usage 02”, obj1 requests the overloaded plus operator.

The result of the above code is shown below:

Source

What happens if we perform the addition like DivBy5 Obj4 = 3 + obj1; ?

We get a compiler error as 3 is not an object and it is not possible to invoke the overloaded + operator. In this situation, we should use the global friend functions to overload the plus operator.

5. Binary operator overloading in c++ using friend function

When we use global friend function, both objects are passed as the parameter to the function. So we know need to worry that the first operand should be an object to take the responsibility of invoking the overloaded operator function. Below is the complete code:

// TestIt.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;

//=========================================================
//Example: Overloaded + Operator as class member function
//=========================================================

class DivBy5
{
public:
    //Sample 01: It acts as Default Constructor as well as 
    // Conversion constructor.
    DivBy5(int number = 0)
    {
        m_theNumber = number;
        m_quotient = m_theNumber/5;
        m_reminder = m_theNumber%5;
    }

    //Sample 02: Print the Reminder and divident
    void print()
    {
        cout<<"Quotient ="<<m_quotient<<endl;
        cout<<"Reminder ="<<m_reminder<<endl;
    }

	////Sample 03: OverLoading Operator +
	//DivBy5 operator+(DivBy5 obj2nd)
	//{
	//	return m_theNumber + obj2nd.m_theNumber;
	//}

    //Sample 04: Overloading Operator using the Friend
    friend DivBy5 operator+(DivBy5 Obj1, DivBy5 Obj2);

private:
    int m_quotient;
    int m_reminder;
    int m_theNumber;
};

//Sample 05: Overloaded operator implementation
DivBy5 operator+(DivBy5 Obj1, DivBy5 Obj2)
{
    return (Obj1.m_theNumber + Obj2.m_theNumber); 
}

void main()
{
    //Usage 01: Construct 2 objects
    DivBy5 obj1(17);
    DivBy5 obj2(22);
    cout<<"Object 1"<<endl;
    obj1.print();
    cout<<"Object 2"<<endl;
    obj2.print();

    //Usage 02: Use the + Operator
    DivBy5 Obj3 = obj1 + obj2;
    cout<<"Object 3"<<endl;
    Obj3.print();

    //Usage 03: Use the + Operator with Const
    DivBy5 Obj4 = obj1 + 3;
    cout<<"Object 4"<<endl;
    Obj4.print();

    //Usage 04: Use the + Operator with Const (2nd way)
    DivBy5 Obj5 = 3 + obj1;
    cout<<"Object 5"<<endl;
    Obj4.print();
}

Explanation

Sample 04: The Overloaded plus operator declared as a Friend function. Note that both the operands are passed as the arguments to the “overloaded + “ operator function.

Sample 05: This snippet is the implementation for the Plus operator overloading function. The Overloaded “+Operator()” function invokes private data member m_theNumber of both the operands and then performs the addition. The added result is returned. Even through function returns the result as an integer; this will be transformed into an object of type DivBy5 as we have the corresponding the conversion constructor.

Usage 05: In the previous section we saw that the usage as shown in the code snippet is not possible as the first operand is not an object and invoking the Plus operator is not possible. But overloading the plus operator as friend function makes the addition 3 + obj1 possible.

The result of executing the program is shown below:

Source

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.