Operator overloading in c++

Introduction to Operator Overloading

Operator overloading is without doubt one of the greatest options of C++. By overloading the operators, we can provide further which means to the operators like +-*/=.,= and so forth., which by default are purported to work solely on commonplace information varieties like int, float, char, void and so forth. It’s a vital idea in C++. It’s a sort of polymorphism through which an operator is overloaded to provide it the user-defined which means.

C++ permits us to specify a couple of definition for a perform title or an operator in the identical scope, which is named perform overloading and operator overloading, respectively. The method of choosing probably the most appropriate overloaded perform 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 probably the greatest options that’s used to overload many of the operators like “+” “” “*” “/” “=” “.” “,” and so forth in c++.

Desk 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 forms of operator overloading?

There are two forms of operator overloading:

  • Operate overloading.
  • Operator overloading.
Types of Operator Overloading

What’s perform overloading?

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

What’s Operator overloading?

 In C++, it may add particular options to the performance and behavior of already present operators like athematic and different operations. The mechanism of giving particular which means to an operator is named operator overloading. For instance, we will 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 perform: It’s within the scope of the category through which it’s declared.
  • Pal perform: It’s a non-member perform of a category with permission to entry each non-public 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
#embody <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<<"https://www.mygreatlearning.com/"<<b;
    }
};

int principal() {
    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 perform
   // complex2 is handed as an argument to the perform
    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

#embody <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 thing are:  "<<endl<< a<<" and " <<b;
    }
};

int principal() {
    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

#embody <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 principal() {
    NotOp obj;
    !obj;
    obj.out();

    return 0;
}
Output 
1
0

Distinction between Member and pal perform

Member perform:

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

Pal Operate:

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

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

  1. To work, no less than 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 pal perform. Nevertheless, such operators could be overloaded utilizing the member perform.

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. Not less than one of many operands in overloaded operators should be user-defined, which suggests we can not overload the minus operator to work with one integer and one double. Nevertheless, you may overload the minus operator to work with an integer and a mystring.
  4.  It isn’t doable to alter the variety of operands of an operator helps.
  5. All operators hold 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++ allows 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 grasp.

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 doable for templates to work equally nicely with lessons and built-in varieties. Operator overloading permits C++ operators to have user-defined meanings on user-defined varieties 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 so forth…

Binary operators:

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

Operator Overloading in Unary Operators

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

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

#embody<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 principal()
{
        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 method for user-defined objects. The binary operators are the operators that work on two operands, similar to addition (+), multiplication (*), and so forth. A single operator can perform a wide range 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.

#embody <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 principal() {
    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 perform
   // T2 is handed as an argument to the perform
    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, it’s essential to know that not all operators could be overloaded. The operators that may be overloaded in C++ are generally known as overloadable operators. Nevertheless, there are some non-overloadable operators as nicely 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 sort 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 scale 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 perform name.

The operators aside from listed above could be overloaded both as a member or as non-members. However on the whole, non-member overloading is advisable. As a result of:

  1. Symmetry: When a binary operator is outlined as a category technique, it will need to 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 ought to 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 technique can not entry non-public member, it tends to make the category much less coupled

Instance:

Utilizing unary operator:
 //Overload ++ when used as prefix
#embody<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 principal()
{
Rely count1;
//name the “void operator ++ ()” perform
++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 will use them to work in any method we like. For instance, we may have used ++ to extend the worth by 100.
Nevertheless, this makes our code extra complicated and obscure. So utilizing operators in overloading appropriately and persistently, and understandably helps simple 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:
Right here, the int contained in the parentheses. It’s the syntax used for utilizing unary operators as postfix; it’s not a perform parameter.

Instance 2: 

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

#embody<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 principal()
{
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 perform
//complex2cis handed as an arguments to the perform
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 perform is:

Advanced operator + (const Complex7 obj)

We will additionally write this perform 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 by utilizing the key phrases:

  1. Personal: Personal entry means member information written beneath this part is accessible by solely member capabilities. They can’t be accessed from outdoors the category or wherever in this system. If no entry specifiers are talked about, then by default, members are handled as non-public.
  2. Public: It signifies that members could be accessed by any perform inside or outdoors the category, however inside a program. The non-public variable top is accessed by the member perform. A number of the public perform of a category offers an interface for accessing the non-public 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 outdoors; It’s just like the non-public 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. Operate overloading and operator overloading are two phrases utilized in C++ to explain the power to specify a number of definitions for a perform 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 international or member capabilities.

What is supposed by operator overloading?

In a type of polymorphism generally known as operator overloading, object-oriented techniques allow the usage of the identical operator title or image for various completely different operations. In different phrases, it allows the operator image or title to be linked to many operator implementations.

What’s operator overloading and its varieties?

The method of fixing the performance of some particular operators to do a brand new process is named operator overloading. Varieties or approaches of operator overloading are as follows:
Overloading of unary operators
Overloading of binary operators
Overloading of binary operators utilizing pal perform (pal key phrase is used to declare the category scope inside a perform)

Why operator overloading is utilized in OOP?

When one or each operands are of a user-defined class or construction sort, operator overloading makes it simpler to specify user-defined implementation for such operations. This makes user-defined varieties extra just like the fundamental primitive information varieties when it comes to 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 a wide range of methods. It refers back to the concept in pc science you can entry objects of many sorts by the identical interface.

What are some great benefits of operator overloading?

It makes it possible for templates to perform equally nicely with lessons 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 lessons.

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

When an operator is overloaded, its authentic operational which means is likely to be expanded upon. Then again, we will assemble a technique in order that it may be known as in a wide range of methods by utilizing perform overloading (also referred to 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++ expertise. To study extra about programming and different associated ideas, try the programs on Nice Studying Academy

Additionally, if you’re 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 prime engineering faculties and universities, together with IIT Madras, Nice Lakes & IIIT Hyderabad. Take part in commonly organized profession accelerated packages and placement drives provided by Nice Studying and get employed by the highest main corporations throughout completely different industries.

By admin

Leave a Reply

Your email address will not be published.