C++ Overloading and Operator Overloading

In the C++ programming language overloading is used for performing more than one task using the same function or operator. For overloading of the functions we create two or more definitions of one function name.

Take a look at an example:


	int add(int a, int b)
	{
		return a+b;
	}

	int add(int a, int b, int c)
	{
		return a+b+c;
	}

As you can see we have two functions with the same name. The first will take two parameters and the second will take three.

Operator overloading

Operator overloading is a concept of overloading of existing operators, so that they can be used in customized ways. The C++ language uses the keyword “operator” for overloading of operators.

It can be used with the following syntax:


	 operator([parameters])
	{
		Statements
	}

An example:


	int operator+(int a, int b)
	{
		return a+b;
	}

The above definition seems to be of no use, but it represents the concept of overloading of operators.

The table below shows all over-loadable operators:

operator overloading

Operator overloading is normally applied on “class” data types, as these are user defined types and operators normally do not work with them. By applying overloading of operators, we can make them (operators) work for user defined types.


#include<iostream>
using namespace std;

class Rational
{
	private:
		double num, den;
	public:
		void get();
		void show();
		Rational add(Rational);
		Rational operator+(Rational);
};

void Rational::get()
{
	cout << endl << "Enter numberator : ";
	cin >> num;
	cout << endl << "Enter Denominator :";
	den=0;
	while(den == 0)
	{
		cin >> den;
		if(den==0)
		{
			cout << endl << "Re-enter (Denominator can not be zero";
		}
	}
}
void Rational::show()
{
	cout << num << "/" << den;
}

Rational Rational::add(Rational arg)
{
	Rational temp;
	temp.num = num * arg.den + den * arg.num;
	temp.den = den * arg.den;
	return temp;
}

Rational Rational::operator+(Rational arg)
{
	Rational temp;
	temp.num = num * arg.den + den * arg.num;
	temp.den = den * arg.den;
	return temp;
}

Note: the use of the operator+ in the last section. (The function main will follow below, without it the program will not compile. So add it first).

The example above shows the use and advantage of operator overloading. Suppose we have 3 objects of the class Rational and 2 of them have some values accepted in them, then the addition process of them can be performed as follows:


     obj3 = obj1.add(obj2);

or


     obj3 = obj1+obj2;

The second approach is more natural and user friendly then the first one.

So the main function (using class above) can look as follows:


int main(int argc, char*argv[])
{
	Rational obj1, obj2, obj3;
	obj1.get(); obj2.get();
	obj3=obj1 + obj2;
	obj3.show();
}

Operators that cannot be overloaded

sizeof

Object size
information

typeid

Object type
information

::

Used to resolve the scope of variable or
function of a class

? :

Ternary Operator (conditional
operator)

. (dot)

Dereferencing
Operator.

.*

Member selection with pointer to
member

The basic reason for unavailability of the above operators is that some of them perform their jobs for the user defined data types, by default and the ternary operator is an operator pair.

That is all for this tutorial. In the next C++ tutorial we will take another look at overloading and operator overloading.

This entry was posted in C++ Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

There are currently 7 responses to “C++ Overloading and Operator Overloading”

Why not let us know what you think by adding your own comment!

  1. shri hari on July 22nd, 2010:

    i could not run the following code;

    float area(int,int,int);//area of triangle
    int area(int);//area of square
    int area(int,int);//area of rectaangle
    float area(int);//area of circle

    float area(int x,int y,int z)
    {
    float s;
    s=(x+y+z)/3;
    return(sqrt(s*(s-x)*(s-y)*(s-z)));
    }

    int area(int a)
    {
    return a*a;
    }

    int area(int l,int b)
    {
    return l*b;
    }

    float area(int r)
    {
    return float((3.14*r*r));
    }

    void main()
    {
    int x,y,z,a,l,b,r;
    float s;
    cout>>x>>y>>z;
    cout<<"\narea="<<area(x,y,z);
    cout>>a;
    cout<<"\narea="<<area(a);
    cout>>l>>b;
    cout<<"\narea="<<area(l,b);
    cout>>r;
    cout<<"\narea="<<area(r);
    getch();
    }

    All the above "area" functions are different, right? pls explain this for me.

  2. admin on July 22nd, 2010:

    @ Shri hari
    Besides all sorts of minor issues, such as using of cout instead of cin, conversion from float to int (possible loss of data), etc.

    The main problem is that you are trying to overload functions that only differ in return type. So int area(int) is the same as float area(int). You should get an error like:
    error C2556: ‘float area(int)’ : overloaded function differs only by return type from ‘int area(int)’
    This is because each overloaded function must have a distinct formal parameter list.

    So the overloading problem we can easily fix by using a float area(float), this also fixes the problem of type conversion (and possible loss of data.) Then combat the problem of unwanted type conversion in float area(int,int,int);//area of triangle, we also change the type of the parameter list to float. Then fix the s=(x+y+z)/3; to s=(x+y+z)/2; and other minor changes. This example should compile without warnings or errors:

    #include <iostream>
    #include <math.h>
    using namespace std;

    int area(int);//area of square
    int area(int,int);//area of rectangle
    float area(float);//area of circle
    float area(float,float,float);//area of triangle

    //area of square
    int area(int a) {
    return a*a;
    }

    //area of rectangle
    int area(int l,int b) {
    return l*b;
    }

    //area of circle
    float area(float r) {
    return float((3.14*r*r));
    }

    //area of triangle
    float area(float x,float y,float z) {
    float s;
    s = (x + y + z) / 2; // Not three as you had!
    return(sqrt(s*(s-x)*(s-y)*(s-z)));
    }

    void main() {
    int a,b;
    float c,d,e;

    cout << “\nInput an integer for area of square:”;
    cin >> a;
    cout << “\narea=” << area(a);

    cout << “\nInput two integers for area of rectangle:”;
    cin >> a >> b;
    cout << “\narea=” << area(a,b);

    cout << “\nInput a float for area of circle:”;
    cin >> c;
    cout << “\narea=” << area(c);

    cout << “\nInput three floats for area of triangle:”;
    cin >> c >> d >> e;
    cout << “\narea=” << area(c,d,e);
    }

    Tip: always try to make your example programs as complete as possible (even if its only for a test) as we did by adding some comment lines and some extra screen output. This will help you in debugging.

    We hope that this example helps you!!

  3. shrihari on July 23rd, 2010:

    thank u.

  4. Praveen on December 7th, 2010:

    I want an example program for ternary operator overloading.

  5. admin on December 9th, 2010:

    The ternary operator (?:) in c++ is cannot be overloaded. Most operators can be overloaded by a programmer. The exceptions are: . (dot) :: ?: sizeof
    On the Stroustrup: c++ style and technique FAQ website he says:

    There is no fundamental reason to disallow overloading of ?:. I just didn’t see the need to introduce the special case of overloading a ternary operator. Note that a function overloading expr1?expr2:expr3 would not be able to guarantee that only one of expr2 and expr3 was executed.

  6. Chaitanya on December 6th, 2011:

    What is the code for the below given operation using Operator Overloading..?
    Class Abc{};
    main()
    { Abc ob1,ob2(10,20),ob3(50,60);
    Abc ob4=ob1+ob2-ob3;
    }

  7. Sudhish on October 13th, 2012:

    @chaitanya it is same with different name, Hope it helps…

    #include
    using namespace std;

    class Rational
    {
    private:
    double num, den;
    public:
    void get();
    void show();
    Rational add(Rational);
    Rational operator+(Rational);
    Rational operator-(Rational);
    };

    void Rational::get()
    {
    cout << endl <> num;
    cout << endl <> den;
    if(den==0)
    {
    cout << endl << "Re-enter (Denominator can not be zero";
    }
    }
    }
    void Rational::show()
    {
    cout << num << "/" << den;
    }

    Rational Rational::add(Rational arg)
    {
    Rational temp;
    temp.num = num * arg.den + den * arg.num;
    temp.den = den * arg.den;
    return temp;
    }

    Rational Rational::operator+(Rational arg)
    {
    Rational temp;
    temp.num = num * arg.den + den * arg.num;
    temp.den = den * arg.den;
    return temp;
    }

    Rational Rational::operator-(Rational arg)
    {
    Rational temp;
    temp.num = num * arg.den – den * arg.num;
    temp.den = den * arg.den;
    return temp;
    }

    int main(int argc, char*argv[])
    {
    Rational obj1, obj2, obj3, obj4;
    obj1.get(); obj2.get(); obj3.get();
    obj4=obj1 + obj2 – obj3;
    obj4.show();
    system("pause");
    return 0;
    }

Leave a Reply: