Sunday, October 2, 2022
HomeArtificial IntelligenceOperator Overloading in C++ with examples

Operator Overloading in C++ with examples


Operator overloading in c++

Introduction to Operator Overloading

Operator overloading is without doubt one of the finest options of C++. By overloading the operators, we can provide extra which means to the operators like +-*/=.,= and many others., which by default are alleged to work solely on customary information varieties like int, float, char, void and many others. It’s a vital idea in C++. It’s a sort of polymorphism during which an operator is overloaded to provide it the user-defined which means.

C++ permits us to specify multiple definition for a perform identify or an operator in the identical scope, which is known as perform overloading and operator overloading, respectively. The method of choosing probably the most appropriate overloaded perform or operator is known as 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 among the finest options that’s used to overload many of the operators like “+” “” “*” “/” “=” “.” “,” and many others 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 sorts of operator overloading?

There are two sorts of operator overloading:

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

What’s perform overloading?

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

What’s Operator overloading?

 In C++, it could 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 during which it’s declared.
  • Good friend perform: It’s a non-member perform 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 primary() {
    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

#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 parts of the item are:  "<<endl<< a<<" and " <<b;
    }
};

int primary() {
    OverLoad obj;
    obj.in();
    --obj;
    obj.out();

    return 0;
}

Output
Enter the primary quantity : 56 
ENter the second quantity : 234 
The decremented parts 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 primary() {
    NotOp obj;
    !obj;
    obj.out();

    return 0;
}
Output 
1
0

Distinction between Member and buddy perform

Member perform:

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

Good friend Perform:

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

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

  1. To work, at the least one of many operands should be a user-defined class object.
  2. We are able to solely overload the prevailing operators, Can’t overload new operators.
  3. Some operators can’t be overloaded utilizing a buddy perform. Nonetheless, such operators could be overloaded utilizing the member perform.

Which operators Can’t be overloaded?

  1. Conditional [?:], measurement of, scope(::), Member selector(.), member pointer selector(.*) and the casting operators.
  2. We are able to solely overload the operators that exist and can’t create new operators or rename present operators.
  3. At the 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 can overload the minus operator to work with an integer and a mystring.
  4.  It’s not attainable to vary 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++ allows programmers to make use of notation nearer to the goal area.
  2. They supply comparable help to built-in sorts 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 attainable 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 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 are able to overload a unary operator like every other operator. We are able to redefine the unary operators to behave in a sure approach on sure operands utilizing unary operator overloading in C++. It’s mainly used for working on user-defined datatypes, like courses and constructions.

Instance: Allow us to 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 primary()
{
        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 are able to redefine the binary operators to function in a sure approach for user-defined objects. The binary operators are the operators that work on two operands, corresponding to addition (+), multiplication (*), and many others. A single operator can perform a wide range of functionalities utilizing two operands offered by the programmer or consumer on this polymorphic compile approach.

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 primary() {
    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 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 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 listing 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 measurement 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 item or datatype. The compiler evaluates this. It can’t be assessed in real-time. We are able to’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 apart from listed above could be overloaded both as a member or as non-members. However normally, non-member overloading is really helpful. 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 consumer is anticipating from the *operator. So, on this case, we should always use no-member operators overloading.
  2. Weak coupling: since a non-member technique 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
Depend() : worth(5)  {}
//overload ++ when used as prefix
Void operator ++ () 
{ 
++worth;
}
Void show()
{
Cout<<”Depend: “<<worth<<endl;
}
};
Int primary()
{
Depend count1;
//name the “void operator ++ ()” perform
++count1:
Count1.show();
Return 0;
}
Output 
Depend:  6
NOTE: 
Right here, Once we use ++count1; , the void operator ++() is known as. 
This will increase the worth attribute for the item rely 1 by 1.
Once we overload the operators, we will use them to work in any approach we like. For instance, we might have used ++ to extend the worth by 100.
Nonetheless, this makes our code extra complicated and obscure. So utilizing operators in overloading appropriately and constantly, and understandably helps simple 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 perform parameter.

Instance 2: 

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

#embrace<iostream.h>
utilizing namespace std;
 class Complicated
{
 Personal:
  float actual;
 float imag;
Public:
//constructor to initialize actual and imag to 0
Complicated() :  actual(0), picture(0)  {}
 void enter()
{
 // overload the + operator
Complicated operator + (const Complex7 obj)
{
Complicated 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 Complicated quantity: “<< “+” << “I”;
}
};
Int primary()
{
Complicated 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 Complicated quantity: 16+11i

On this program, the operator perform is:

Complicated operator + (const Complex7 obj)

We are able to additionally write this perform like:

Complicated operator + (Complicated  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 below 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 personal.
  2. Public: It implies that members could be accessed by any perform inside or outdoors the category, however inside a program. The personal variable top is accessed by means of the member perform. A number of the public perform of a category offers 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, mates of the category, and member capabilities derived from this class. The members can’t be accessed from outdoors; It’s just like the personal members.

Operator Overloading in C++ FAQs

What’s operator overloading in C++?

An operator is overloaded in one of these 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 perform identify 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 may be world or member capabilities.

What is supposed by operator overloading?

In a type of polymorphism often called operator overloading, object-oriented methods allow the usage of the identical operator identify or image for quite a lot of completely different operations. In different phrases, it allows the operator image or identify to be related 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. Sorts or approaches of operator overloading are as follows:
Overloading of unary operators
Overloading of binary operators
Overloading of binary operators utilizing buddy perform (buddy 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 by way of behaviour.

What’s polymorphism in oops?

One of many elementary 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 that you could entry objects of many varieties by means of the identical interface.

What are some great benefits of operator overloading?

It makes it possible for templates to perform equally properly with courses and built-in/intrinsic varieties 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 varieties due to operator overloading like courses.

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

When an operator is overloaded, its authentic operational which means may be expanded upon. However, we will assemble a way in order that it may be known as in a wide range of methods by utilizing perform 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 be taught extra about programming and different associated ideas, try the programs on Nice Studying Academy

Additionally, in case you are 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 program Engineering Programs at Nice Studying in collaboration with prime engineering schools and universities, together with IIT Madras, Nice Lakes & IIIT Hyderabad. Take part in frequently organized profession accelerated applications and placement drives supplied by Nice Studying and get employed by the highest main corporations throughout completely different industries.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments