Operator Overloading in C++
Operator overloading is a type of polymorphism supported by C++. Operator overloading allows us to redefine the operation of the basic operators to be applied on user-defined classes and data types.
For example if we have defined a class and there are two objects of this class, then we might like to do an operation like below.
object1 + object2
The default behavior of + operator does not allow us to use + operator for this purpose. But C++ allows us to redefine + operator to perform the intended operation. Similarly, we might like to store the result of above operation in another object of the class as below.
object3 = object1 + object2
In the above expression apart from + operator, = operator is used to store the result of operation in object3. Again + operator does not allow us to do so but can be redefined to achieve the above intended objective.
The following example shows that how + and = operators can be overloaded to achieve the objective discussed above.
We can see that + operator is declared for overloading at line 9 and = operator is declared for overloading at line 10. The = operator is overloaded in lines 12 to 18 and + operator is overloaded in lines 19 t 25. The + operator is redefined to add the corresponding data members of two objects of the same class and = operator is redefined to store the (calculated) data members to another object of the same class. The following code shows that how that how to make use of the above code.
The overloaded + and = operators are used at line 40 producing the following output.
From the above output it is clear that + operator is redefined to add the data members of two objects of Box class and = operator is redefined to store the result in another object of Box class.
More Related Articles For You
- What is C++
- C++ and Object Oriented Programming OOPS concepts
- Syntax and Structure of C++ program
- Data Types in C++
- C++ Variables
- Types of operators in C++
- Decision making in C++
- C++ Loop Types
- Storage Classes in C++
- Functions in C++
- Classes and Objects in C++
- Access controls in C++ Classes
- Defining Class and Object in C++
- Accessing Public and Private Data Members in C++
- Member Functions in Classes
- Types of Member Functions in C++
- Inline Functions in C++
- Namespaces in C++
- Function Overloading in Classes in C++
- Constructors and Destructors in C++
- Static Keywords in C++
- Const Keyword in C++ Programming
- References in C++
- Copy Constructor in C++
- Pointer to Members in C++ Classes
- Introduction to Inheritance
- Types of Inheritance
- Order of Constructor Call in Inheritance
- Upcasting in C++
- Function Overriding in C++
- Virtual Functions in C++
- Abstract Class and Pure Virtual Functions in C++
- Virtual Destructors in C++