Looking for a Tutor Near You?

Post Learning Requirement »
x

Choose Country Code

x

Direction

x

Ask a Question

x

x
x
x
Hire a Tutor

Notes On Operator Overloading InC++

Loading...

Published in: C / C++ | Computer Science
1,146 Views

Most of the C++ built-in operators can be redefined or overloaded. Thus, operators can be used with user-defined types as well (for example, allowing you to add two objects together).

Prantik S / Kolkata

11 years of teaching experience

Qualification: MCA (Jaipur National University - [JNU], Jaipur - 2017)

Teaches: Basic Computer, Computer for official job, MS Office, School Level Computer, ICT Training, Computer Science, Information Practice, IT & Computer Subjects, BCA Tuition, IT, Computer, C / C++, C# (C Sharp), Java And J2EE, Python Programming, Visual Basic, BCA Subjects, Hardware Training, Networking, Java Script

Contact this Tutor
  1. Operator Overloading in C++ Most of the C++ built-in operators can be redefined or overloaded. Thus, operators can be used with user-defined types as well (for example, allowing you to add two objects together). This chart shows the operators that can be overloaded. new new 0 delete delete[l Operators that can't be overloaded include :: I I Overloaded operators are functions, defined by the keyword operator followed by the symbol for the operator being defined.
  2. An overloaded operator is similar to other functions in that it has a return type and a parameter list. In our example we will be overloading the + operator. It will return an object of our class and take an object of our class as its parameter. class MyClass { public: int var; MyClass() {} MyClass(int a) : var(a) { } MyClass operator+(MyClass &obj) { Note: Now, we need to define what the function does. We need our + operator to return a new MyClass object with a member variable equal to the sum of the two objects' member variables. Here, we declared a new res object. We then assigned the sum of the member variables of the current object (this) and the parameter object (obj) to the res object's var member variable. The res object is returned as the result. This gives us the ability to create objects in main and use the overloaded + operator to add them together. #include using namespace std;
  3. class MyClass { public: int var; MyClass() { } MyClass(int a) : var(a) { } MyClass operator+(MyClass &obj) { MyClass res; res.var= this->var+0bj.var; return res; int main() { MyClass obj1(12), obj2(55); MyClass res = obj1+0bj2; cout