Introduction to Operator Overloading
Operator overloading is likely one of the finest options of C++. By overloading the operators, we can provide extra that means to the operators like +-*/=.,= and many others., which by default are presupposed to work solely on customary knowledge sorts like int, float, char, void and many others. It is a necessary idea in C++. It’s a kind of polymorphism during which an operator is overloaded to offer 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 known as operate overloading and operator overloading, respectively. The course of of choosing probably the most appropriate overloaded operate or operator is known as overload decision.
So now let’s perceive what’s operator overloading in c++.
What is operator overloading in C++?
Operator overloading in c++ is outlined as among the best options that’s used to overload a lot of the operators like “+” “–” “*” “/” “=” “.” “,” and many others in c++.
Table of contents:
What are Operators?
An operator is an emblem that tells the compiler to carry out particular mathematical, logical calculations or another particular operations.
What are the varieties of operator overloading?
There are two varieties of operator overloading:
- Function overloading.
- Operator overloading.
What is operate overloading?
The course of of getting two or extra capabilities with the identical title however with totally different parameters (arguments) is known as operate overloading. The operate is redefined by both utilizing several types of arguments or a special variety of arguments. It is barely by means of these variations {that a} compiler can differentiate between capabilities.
What is Operator overloading?
In C++, it may possibly 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 *
- Memory administration operator: new, delete []
Implementing Operator overloading:
- Member operate: It is within the scope of the category during which it’s declared.
- Friend operate: It is a non-member operate of a category with permission to entry each non-public and guarded members.
Learn Different C++ Concepts For Free
Operator Overloading Examples
Example 1: Let us multiply two fractions utilizing the overloading of the multiplication operator in C++.
// Multiplication of two fractions
#embrace <iostream>
utilizing namespace std;
class Frac {
non-public:
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<<"/ "<<b;
}
};
int essential() {
Frac F1, F2, outcome;
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
outcome = F1 * F2;
outcome.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
Example 2: A C++ program to overload a prefix decrement operator
#embrace <iostream>
utilizing namespace std;
class OverLoad {
non-public:
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 article are: "<<endl<< a<<" and " <<b;
}
};
int essential() {
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
Example 3: Overloading a NOT (!) operator
#embrace <iostream>
utilizing namespace std;
class NotOp {
non-public:
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 essential() {
NotOp obj;
!obj;
obj.out();
return 0;
}
Output
1
0
Difference between Member and pal operate
Member operate:
- The variety of parameters to be handed is diminished by one, because the calling object is implicitly equipped is an operand.
- Unary operators tales no express parameters.
- Binary operators take just one express parameter.
Friend Function:
- More parameters may be handed.
- Unary operators take one express parameter.
- Binary operators take two express parameters.
What are the principles for operator overloading in C++?
- To work, at the least one of many operands should be a user-defined class object.
- We can solely overload the prevailing operators, Can’t overload new operators.
- Some operators can’t be overloaded utilizing a pal operate. However, such operators may be overloaded utilizing the member operate.
Which operators Cannot be overloaded?
- Conditional [?:], dimension of, scope(::), Member selector(.), member pointer selector(.*) and the casting operators.
- We can solely overload the operators that exist and can’t create new operators or rename present operators.
- At least one of many operands in overloaded operators should be user-defined, which implies we can not overload the minus operator to work with one integer and one double. However, you would overload the minus operator to work with an integer and a mystring.
- It will not be attainable to vary the variety of operands of an operator helps.
- All operators preserve their default priority and associations (what they use for), which can’t be modified.
- Only built-in operators may be overloaded.
Advantages of an operator overloading in C++
- Operator overloading in c++ allows programmers to make use of notation nearer to the goal area.
- They present related help to built-in varieties of user-defined sorts.
- Operator overloading in c++ makes this system simpler to grasp.
Disadvantages of an operator overloading in C++
In operator overloading, any C++ present operations may be overloaded, however some exceptions.
The want for operator overloading in C++
It permits us to offer an intuitive interface to our class customers, plus makes it attainable for templates to work equally effectively with lessons and built-in sorts. Operator overloading permits C++ operators to have user-defined meanings on user-defined sorts or lessons.
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 known as unary operators.
- Examples: Increment operators(++), Decrement operators(–),unary minus operator(-), Logical not operator(!) and many others…
Binary operators:
- Operators which works on Two operands are known as binary operator.
Operator Overloading in Unary Operators
We can overload a unary operator like some other operator. We can redefine the unary operators to behave in a sure means on sure operands utilizing unary operator overloading in C++. It is mainly used for working on user-defined datatypes, like lessons and constructions.
Example: Let us strive overloading the increment and decrement operators by means of 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 essential()
{
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 can 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, akin to addition (+), multiplication (*), and many others. A single operator can perform a wide range of functionalities utilizing two operands supplied by the programmer or consumer on this polymorphic compile method.
Example: Let us see the next C++ code that elaborates the overloading of the addition operator.
#embrace <iostream>
utilizing namespace std;
class Time {
non-public:
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 essential() {
Time T1, T2, outcome;
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
outcome = T1 + T2;
outcome.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 simply noticed the overloading of unary and binary operators in C++ within the earlier sections of this weblog, you will need to know that not all operators may be overloaded. The operators that may be overloaded in C++ are often known as overloadable operators. However, there are some non-overloadable operators as effectively 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 vital programming issues. As an illustration, the sizeof operator returns the operand, which is the scale of the article or datatype. The compiler evaluates this. It can’t be assessed in real-time. We can’t thus overburden it.
Overloading particular operators in C++
Some of the particular operators in C++ are as follows:
- new – It is used to allocate the reminiscence dynamically.
- Delete – It is used to free the reminiscence dynamically.
- [] – It is a subscript operator.
- -> – – It is a member entry operators.
- = – It is used to assign the values.
- () – It is used for operate name.
The operators apart from listed above may be overloaded both as a member or as non-members. But usually, non-member overloading is advisable. Because:
- Symmetry: When a binary operator is outlined as a category technique, it will need to have objects as its operands. We ought to 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 ought to be the identical as b*a. Otherwise, it breaks the cumulativeness that the consumer is anticipating from the *operator. So, on this case, we should always use no-member operators overloading.
- Weak coupling: since a non-member technique can not entry non-public member, it tends to make the category much less coupled
Example:
Using unary operator:
//Overload ++ when used as prefix
#embrace<iostream.h>
Using namespace std;
Class depend
{
Private:
Int worth;
Public:
//constructor to initialize depend to five
Count() : worth(5) {}
//overload ++ when used as prefix
Void operator ++ ()
{
++worth;
}
Void show()
{
Cout<<”Count: “<<worth<<endl;
}
};
Int essential()
{
Count count1;
//name the “void operator ++ ()” operate
++count1:
Count1.show();
Return 0;
}
Output
Count: 6
NOTE: Here, When we use ++count1; , the void operator ++() is known as. This will increase the worth attribute for the article depend 1 by 1. When we overload the operators, we are able to use them to work in any means we like. For instance, we might have used ++ to extend the worth by 100. However, this makes our code extra complicated and obscure. So utilizing operators in overloading accurately and persistently, and understandably helps straightforward to grasp 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: Here, the int contained in the parentheses. It’s the syntax used for utilizing unary operators as postfix; it’s not a operate parameter.
Example 2:
//C++ program to overload the binary operator +
//This program provides two advanced numbers
#embrace<iostream.h>
utilizing namespace std;
class Complex
{
Private:
float actual;
float imag;
Public:
//constructor to initialize actual and imag to 0
Complex() : actual(0), picture(0) {}
void enter()
{
// overload the + operator
Complex operator + (const Complex7 obj)
{
Complex temp;
temp.actual = actual +obj.actual;
temp.imag = imag +obj.imag;
return temp;
}
void output()
{
If(imag<0)
Cout<< “OutputComplex number: ” << actual << “i”;
else
depend<< “Output Complex number: “<< “+” << “I”;
}
};
Int essential()
{
Complex complex1, complex2,outcome;
Cout<< “Enter first advanced quantity:n;
Complex1.enter();
Cout<< “Enter second complex number:n”;
Complex2.enter();
//complex1 calls the operator operate
//complex2cis handed as an arguments to the operate
outcome = complex1 + complex2;
outcome.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 Complex quantity: 16+11i
In this program, the operator operate is:
Complex operator + (const Complex7 obj)
We may write this operate like:
Complex operator + (Complex obj)
{
//code
}
Access specifiers
Every 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 by utilizing the key phrases:
- Private: Private entry means member knowledge written underneath this part is accessible by solely member capabilities. They can’t be accessed from exterior the category or anyplace in this system. If no entry specifiers are talked about, then by default, members are handled as non-public.
- Public: It implies that members may be accessed by any operate inside or exterior the category, however inside a program. The non-public variable peak is accessed by means of the member operate. Some of the general public operate of a category supplies an interface for accessing the non-public and guarded class members.
- Protected: The class members of this part are accessible by the member capabilities of the identical class, associates of the category, and member capabilities derived from this class. The members can’t be accessed from exterior; It is much like the non-public members.
Operator Overloading in C++ FAQs
An operator is overloaded in this sort of polymorphism to offer it the user-defined semantics. Function overloading and operator overloading are two phrases utilized in C++ to explain the power to specify a number of definitions for a operate title or an operator in the identical scope
For probably the most half, C++’s built-in operators can have their capabilities redefined or overloaded. Both globally and by class, these operators could also be overloaded. Embedded as capabilities, overloaded operators may be international or member capabilities.
In a type of polymorphism often known as operator overloading, object-oriented techniques allow the usage of the identical operator title or image for a lot of totally different operations. In different phrases, it allows the operator image or title to be linked to many operator implementations.
The course of of adjusting the performance of some particular operators to do a brand new activity is called operator overloading. Types or approaches of operator overloading are as follows:
Overloading of unary operators
Overloading of binary operators
Overloading of binary operators utilizing pal operate (pal key phrase is used to declare the category scope inside a operate)
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 sorts extra much like the fundamental primitive knowledge sorts when it comes to behaviour.
One of the elemental concepts of object-oriented programming (OOP), polymorphism addresses circumstances the place one thing occurs in a wide range of methods. It refers back to the thought in pc science which you could entry objects of many varieties by means of the identical interface.
It makes it possible for templates to operate equally effectively with lessons and built-in/intrinsic sorts whereas additionally enabling you to current customers of your class with an intuitive consumer interface. C/C++ operators can have user-defined meanings on user-defined sorts because of operator overloading like lessons.
When an operator is overloaded, its unique operational that means may be expanded upon. On the opposite hand, we are able to assemble a way in order that it may be known as in a wide range of methods by utilizing operate overloading (often known as technique overloading).
This brings us to the top of the weblog on Operator Overloading in C++. Hope this lets you up-skill your C++ abilities. To study extra about programming and different associated ideas, try the programs on Great Learning Academy.
Also, if you’re making 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 Engineering Courses at Great Learning in collaboration with prime engineering faculties and universities, together with IIT Madras, Great Lakes & IIIT Hyderabad. Participate in commonly organized profession accelerated applications and placement drives provided by Great Learning and get employed by the highest main firms throughout totally different industries.