ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)