Operator Overloading in C++ with examples


Operator overloading in c++

Introduction to Operator Overloading

Operator overloading is likely one of the finest options of C++. By overloading the operators, we may give further that means to the operators like +-*/=.,= and so forth., which by default are purported to work solely on customary knowledge varieties like int, float, char, void and so forth. It’s a necessary idea in C++. It’s a kind of polymorphism by which an operator is overloaded to provide it the user-defined that means.

C++ permits us to specify a couple of definition for a operate title or an operator in the identical scope, which is named operate overloading and operator overloading, respectively. The method of choosing probably the most appropriate overloaded operate or operator is named overload decision.

So now let’s perceive what’s operator overloading in c++.

What’s operator overloading in C++?

Operator overloading in c++ is outlined as the most effective options that’s used to overload a lot of the operators like “+” “” “*” “/” “=” “.” “,” and so forth in c++.

Desk of contents:

What are Operators?

An operator is a logo that tells the compiler to carry out particular mathematical, logical calculations or another particular operations.

What are the forms of operator overloading?

There are two forms of operator overloading:

  • Perform overloading.
  • Operator overloading.
Types of Operator Overloading

What’s operate overloading?

The method of getting two or extra capabilities with the identical title however with completely different parameters (arguments) is named operate overloading. The operate is redefined by both utilizing various kinds of arguments or a unique variety of arguments. It is just via these variations {that a} compiler can differentiate between capabilities.

What’s Operator overloading?

 In C++, it could actually add particular options to the performance and behavior of already present operators like athematic and different operations. The mechanism of giving particular that means to an operator is called operator overloading. For instance, we are able to overload an operator ‘+’ in a class-like string to concatenate two strings by simply utilizing +. 

Operations that may be carried out:

  • Athematic operations: + – * / %
  • Logical operations:  && and ||
  • Relational operations: == != >= <=
  • Pointer operators: & and *
  • Reminiscence administration operator: new, delete []

Implementing Operator overloading:

  • Member operate: It’s within the scope of the category by which it’s declared.
  • Good friend operate: It’s a non-member operate of a category with permission to entry each personal and guarded members. 

Operator Overloading Examples

Instance 1: Allow us to multiply two fractions utilizing the overloading of the multiplication operator in C++.

// Multiplication of two fractions
#embrace <iostream>
utilizing namespace std;

class Frac {
   personal:
    int a;
    int b;

   public:
    Frac() : a(0), b(0) {}

    void in() {
        cout << "Enter the numerator : ";
        cin >> a;
        cout<< "Enter the denominator : ";
        cin >> b;
    }

    // Overload the * operator
    Frac operator * (const Frac &obj) {
        Frac temp;
        temp.a = a * obj.a;
        temp.b = b * obj.b;
       
        return temp;
    }

    void out() {
      cout<<"The fraction is  "<< a<<"https://www.mygreatlearning.com/"<<b;
    }
};

int most important() {
    Frac F1, F2, end result;

    cout << "Enter the primary fraction:n";
    F1.in();

    cout << "Enter the second fraction:n";
    F2.in();

   // complex1 calls the operator operate
   // complex2 is handed as an argument to the operate
    end result = F1 * F2;
    end result.out();

    return 0;
}

OutPut
Enter the primary fraction:
Enter the numerator : 2
Enter the denominator : 5 
Enter the second fraction:
ENter the numerator: 12
Enter the denominator: 7
The fraction is 24/35

Instance 2: A C++ program to overload a prefix decrement operator

#embrace <iostream>
utilizing namespace std;

class OverLoad {
   personal:
    int a;
    int b;

   public:
    OverLoad() : a(0), b(0) {}

    void in() {
        cout << "Enter the primary quantity : ";
        cin >> a;
        cout<< "Enter the second quantity : ";
        cin >> b;
    }

    // Overload the prefix decrement operator
    void operator-- () {
        a= --a;
        b= --b;
    }

    void out() {
      cout<<"The decremented components of the thing are:  "<<endl<< a<<" and " <<b;
    }
};

int most important() {
    OverLoad obj;
    obj.in();
    --obj;
    obj.out();

    return 0;
}

Output
Enter the primary quantity : 56 
ENter the second quantity : 234 
The decremented components fo the objects are: 55 and 223

Instance 3: Overloading a NOT (!) operator

#embrace <iostream>
utilizing namespace std;

class NotOp {
   personal:
    int a;
    bool b;

   public:
    NotOp() : a(0), b(true) {}

    void in() {
        cout << "Enter the primary quantity : ";
        cin >> a;
        cout<< "Enter true or false : ";
        cin >> b;
    }

    // Overloading the NOT (!)  operator
    void operator ! () {
        a= !a;
        b= !b;
    }

    void out() {
      cout<<"Output: "<<endl<< a<<endl<<b;
    }
};

int most important() {
    NotOp obj;
    !obj;
    obj.out();

    return 0;
}
Output 
1
0

Distinction between Member and good friend operate

Member operate:

  1. The variety of parameters to be handed is diminished by one, because the calling object is implicitly equipped is an operand.
  2. Unary operators tales no express parameters.
  3. Binary operators take just one express parameter.

Good friend Perform:

  1. Extra parameters could be handed.
  2. Unary operators take one express parameter.
  3. Binary operators take two express parameters.

What are the principles for operator overloading in C++?

  1. To work, a minimum of one of many operands should be a user-defined class object.
  2. We will solely overload the prevailing operators, Can’t overload new operators.
  3. Some operators can’t be overloaded utilizing a good friend operate. Nonetheless, such operators could be overloaded utilizing the member operate.

Which operators Can’t be overloaded?

  1. Conditional [?:], dimension of, scope(::), Member selector(.), member pointer selector(.*) and the casting operators.
  2. We will solely overload the operators that exist and can’t create new operators or rename present operators.
  3. At the very least one of many operands in overloaded operators should be user-defined, which suggests we can’t overload the minus operator to work with one integer and one double. Nonetheless, you may overload the minus operator to work with an integer and a mystring.
  4.  It’s not potential to alter the variety of operands of an operator helps.
  5. All operators preserve their default priority and associations (what they use for), which can’t be modified.
  6. Solely built-in operators could be overloaded.

Benefits of an operator overloading in C++

  1. Operator overloading in c++ permits programmers to make use of notation nearer to the goal area.
  2. They supply comparable assist to built-in forms of user-defined varieties.
  3. Operator overloading in c++ makes this system simpler to know.

Disadvantages of an operator overloading in C++

In operator overloading, any C++ present operations could be overloaded, however some exceptions.

The necessity for operator overloading in C++

It permits us to offer an intuitive interface to our class customers, plus makes it potential for templates to work equally properly with courses and built-in varieties. Operator overloading permits C++ operators to have user-defined meanings on user-defined varieties or courses.

The syntax for operator overloading:

Class class_name
	{
  		………………….
		…………………..
	Public 
		Return_type operator image (argument ())
		{
			……………….
			……………….
		}
	………………………….
};

Unary Operators and Binary Operator overloading

Unary operators:

  • Operators which work on a single operand are referred to as unary operators.
  • Examples: Increment operators(++), Decrement operators(–),unary minus operator(-), Logical not operator(!) and so forth…

Binary operators:

  • Operators which works on Two operands are referred to as binary operator.

Operator Overloading in Unary Operators

We will overload a unary operator like every other operator. We will redefine the unary operators to behave in a sure means on sure operands utilizing unary operator overloading in C++. It’s principally used for working on user-defined datatypes, like courses and constructions.

Instance: Allow us to attempt overloading the increment and decrement operators via a C++ program.

#embrace<iostream>
utilizing namespace std;

class UnaryOverload
{
        int hr, min;
     public:
        void in()
        {
                cout<<"n Enter the time: n";
                cin>>hr;
                cout<<endl;
                cin>>min;
        }
        void operator++(int) //Overload Unary Increment
        {
                hr++;
                min++;
        }
        void operator--(int) //Overload Unary Decrement
        {
                hr--;
                min--;
        }
        
        void out()
        {
                cout<<"nTime is "<<hr<<"hr "<<min<<"min";
               
        }
};
int most important()
{
        UnaryOverload ob;
        ob.in();
        ob++;
        cout<<"nn After Incrementing : ";
        ob.out();
        ob--;
        ob--;
        cout<<"nn After Decrementing : ";
        ob.out();
        return 0;
}
Output
Enter the time: 
5
56
After Incrementing:
Time is 6hr 57 minutes
After Decrementing:
Time is 4hr 55 min

Operator Overloading in Binary Operators

We will redefine the binary operators to function in a sure means for user-defined objects. The binary operators are the operators that work on two operands, corresponding to addition (+), multiplication (*), and so forth. A single operator can perform quite a lot of functionalities utilizing two operands supplied by the programmer or person on this polymorphic compile method.

Instance: Allow us to see the next C++ code that elaborates the overloading of the addition operator.

#embrace <iostream>
utilizing namespace std;

class Time {
   personal:
    int hour;
    int minute;

   public:
    Time() : hour(0), minute(0) {}

    void in() {
        cout << "Enter the time: ";
        cin >> hour;
        cin >> minute;
    }

    // Overload the + operator
    Time operator + (const Time & obj) {
        Time temp;
        temp.hour = hour + obj.hour;
        temp.minute = minute + obj.minute;
        if (temp.minute>=60)
        {
            temp.hour+=1;
            temp.minute-=60;
        }
        if (temp.hour>24)
        temp.hour=1;
        return temp;
    }

    void out() {
      cout<<"Time is "<< hour<<"hrs "<<minute<<"min";
    }
};

int most important() {
    Time T1, T2, end result;

    cout << "Enter first time in hours and minutes one after the other :n";
    T1.in();

    cout << "Enter second time in hours and minutes one after the other :n";
    T2.in();

   // T1 calls the operator operate
   // T2 is handed as an argument to the operate
    end result = T1 + T2;
    end result.out();

    return 0;
}

Output
Enter first time in hours and minutes one after the other:
Enter the time:11
56
Enter second time in hours and minutes one after the other:
Enter the time: 2
10
Time is 14hrs 6 min

Overloadable/Non-overloadable Operators

Now that you just noticed the overloading of unary and binary operators in C++ within the earlier sections of this weblog, you should know that not all operators could be overloaded. The operators that may be overloaded in C++ are often called overloadable operators. Nonetheless, there are some non-overloadable operators as properly that may’t be overloaded. 

The checklist of non-overloadable operators goes as follows:

  • Ternary operator (? 🙂
  • Dot operator or member entry operator (.)
  • Pointer to member operator (.*)
  • Scope decision operator ( :: )
  • Object kind operator (typeid)
  • Object dimension operator (sizeof)

These operators can’t be overloaded as a result of doing so will trigger important programming issues. As an illustration, the sizeof operator returns the operand, which is the dimensions of the thing or datatype. The compiler evaluates this. It can’t be assessed in real-time. We will’t thus overburden it.

Overloading particular operators in C++

A number of the particular operators in C++ are as follows:

  1. new – It’s used to allocate the reminiscence dynamically.
  2. Delete – It’s used to free the reminiscence dynamically.
  3. [] – It’s a subscript operator.
  4. -> – – It’s a member entry operators.
  5. = – It’s used to assign the values.
  6. () – It’s used for operate name.

The operators apart from listed above could be overloaded both as a member or as non-members. However generally, non-member overloading is really helpful. As a result of:

  1. Symmetry: When a binary operator is outlined as a category methodology, it should have objects as its operands. We must always write like advanced*5 however not like 5*advanced as a result of 5. operator*(advanced)doesn’t make any sense. In different phrases, a*b must be the identical as b*a. In any other case, it breaks the cumulativeness that the person is anticipating from the *operator. So, on this case, we must always use no-member operators overloading.
  2. Weak coupling: since a non-member methodology can’t entry personal member, it tends to make the category much less coupled

Instance:

Utilizing unary operator:
 //Overload ++ when used as prefix
#embrace<iostream.h>
Utilizing namespace std;
Class rely
{ 
 Personal:
 Int worth;
 Public:
//constructor to initialize rely to five
Rely() : worth(5)  {}
//overload ++ when used as prefix
Void operator ++ () 
{ 
++worth;
}
Void show()
{
Cout<<”Rely: “<<worth<<endl;
}
};
Int most important()
{
Rely count1;
//name the “void operator ++ ()” operate
++count1:
Count1.show();
Return 0;
}
Output 
Rely:  6
NOTE: 
Right here, Once we use ++count1; , the void operator ++() is named. 
This will increase the worth attribute for the thing rely 1 by 1.
Once we overload the operators, we are able to use them to work in any means we like. For instance, we may have used ++ to extend the worth by 100.
Nonetheless, this makes our code extra complicated and obscure. So utilizing operators in overloading appropriately and persistently, and understandably helps straightforward to know with none difficulties.
The above-given instance works when ++ is used as a prefix to make ++ works as a postfix; we use this syntax.
Syntax:
Right here, the int contained in the parentheses. It’s the syntax used for utilizing unary operators as postfix; it’s not a operate parameter.

Instance 2: 

//C++ program to overload the binary operator +
//This program provides two advanced numbers

#embrace<iostream.h>
utilizing namespace std;
 class Advanced
{
 Personal:
  float actual;
 float imag;
Public:
//constructor to initialize actual and imag to 0
Advanced() :  actual(0), picture(0)  {}
 void enter()
{
 // overload the + operator
Advanced operator + (const Complex7 obj)
{
Advanced temp;
temp.actual = actual +obj.actual;
temp.imag = imag +obj.imag;
return temp;
}

void output()
{
If(imag<0)
 Cout<< “OutputComplex quantity: ” << actual << “i”;
else
rely<< “Output Advanced quantity: “<< “+” << “I”;
}
};
Int most important()
{
Advanced complex1, complex2,end result;
Cout<< “Enter first advanced quantity:n;
Complex1.enter();
Cout<< “Enter second advanced quantity:n”;
Complex2.enter();

//complex1 calls the operator operate
//complex2cis handed as an arguments to the operate
end result = complex1 + complex2;
end result.output();
}
Output:
Enter a primary advanced quantity:
Enter actual and imaginary elements respectively: 9 5
Enter a second advanced quantity:
Enter actual and imaginary elements respectively: 7 ^
Output Advanced quantity: 16+11i

On this program, the operator operate is:

Advanced operator + (const Complex7 obj)

We will additionally write this operate like:

Advanced operator + (Advanced  obj)
{
//code
}

Entry specifiers

Each member of a category is specified by 3 ranges of entry safety. These are used to outline the scope of members of a category.

The entry specifiers are indicated through the use of the key phrases:

  1. Personal: Personal entry means member knowledge written underneath this part is accessible by solely member capabilities. They can’t be accessed from exterior the category or wherever in this system. If no entry specifiers are talked about, then by default, members are handled as personal.
  2. Public: It implies that members could be accessed by any operate inside or exterior the category, however inside a program. The personal variable top is accessed via the member operate. A number of the public operate of a category gives an interface for accessing the personal and guarded class members.
  3. Protected: The category members of this part are accessible by the member capabilities of the identical class, pals of the category, and member capabilities derived from this class. The members can’t be accessed from exterior; It’s just like the personal members.

Operator Overloading in C++ FAQs

What’s operator overloading in C++?

An operator is overloaded in such a polymorphism to provide it the user-defined semantics. Perform overloading and operator overloading are two phrases utilized in C++ to explain the flexibility to specify a number of definitions for a operate title or an operator in the identical scope

Can we overload operator in CPP?

For probably the most half, C++’s built-in operators can have their capabilities redefined or overloaded. Each globally and by class, these operators could also be overloaded. Embedded as capabilities, overloaded operators is likely to be world or member capabilities.

What is supposed by operator overloading?

In a type of polymorphism often called operator overloading, object-oriented methods allow using the identical operator title or image for numerous completely different operations. In different phrases, it permits the operator image or title to be linked to many operator implementations.

What’s operator overloading and its varieties?

The method of adjusting the performance of some particular operators to do a brand new job is called operator overloading. Varieties or approaches of operator overloading are as follows:
Overloading of unary operators
Overloading of binary operators
Overloading of binary operators utilizing good friend operate (good friend key phrase is used to declare the category scope inside a operate)

Why operator overloading is utilized in OOP?

When one or each operands are of a user-defined class or construction kind, operator overloading makes it simpler to specify user-defined implementation for such operations. This makes user-defined varieties extra just like the fundamental primitive knowledge varieties by way of behaviour.

What’s polymorphism in oops?

One of many basic concepts of object-oriented programming (OOP), polymorphism addresses circumstances the place one thing occurs in quite a lot of methods. It refers back to the thought in laptop science that you may entry objects of many varieties via the identical interface.

What are the benefits of operator overloading?

It makes it possible for templates to operate equally properly with courses and built-in/intrinsic varieties whereas additionally enabling you to current customers of your class with an intuitive person interface. C/C++ operators can have user-defined meanings on user-defined varieties due to operator overloading like courses.

What’s the distinction between operate overloading and operator overloading?

When an operator is overloaded, its authentic operational that means is likely to be expanded upon. Then again, we are able to assemble a technique in order that it may be referred to as in quite a lot of methods through the use of operate overloading (also called methodology overloading).

This brings us to the tip of the weblog on Operator Overloading in C++. Hope this lets you up-skill your C++ expertise. To study extra about programming and different associated ideas, try the programs on Nice Studying Academy

Additionally, in case you are getting ready for Interviews, try these Interview Questions for C++ to ace it like a professional.

For a certificates in C++, take the free course on C++. If you wish to deep dive additional, do try our Software program Engineering Programs at Nice Studying in collaboration with high engineering faculties and universities, together with IIT Madras, Nice Lakes & IIIT Hyderabad. Take part in repeatedly organized profession accelerated packages and placement drives supplied by Nice Studying and get employed by the highest main corporations throughout completely different industries.

Leave a Reply