UNIT III Operator Overloading and Type Conversion
UNIT III Operator Overloading and Type Conversion
The Keyword Operator, Overloading Unary Operator, Operator Return Type, Overloading
Assignment Operator (=), Rules for Overloading Operators, Inheritance, Reusability, Types of
Inheritance, Virtual Base Classes- Object as a Class Member, Abstract Classes, Advantages of
Inheritance, Disadvantages of Inheritance.
Operator overloading in C++ refers to the ability to redefine or customize the behavior
of certain operators when they are used with user-defined data types (classes and
structs).
This allows you to provide a specific meaning or action for operators beyond their built-
in functionality.
Basically, Overloading in C++ is the process of creating two or more members with the
same name but differing numbers or types of parameters.
When it comes to operator overloading in C++ program, we can overload the following
operators:
Binary operators
Unary operators
Special operators
Here is a table representing all the operators with examples that you can overload in C++:
Subscript operator []
The only existing operator can be overloaded. New operators cannot be overloaded.
Every overloaded operator must contain at least one operand of user-defined datatype.
During operator overloading, we cannot change the basic meaning of operators.
If unary operators are overloaded by a member function, then they take no explicit
arguments. But if they are overloaded through a friend function, then take one
argument.
If binary operators are overloaded by a member function, then they take one explicit
argument. But, if they are overloaded through a friend function, then take two
arguments.
Syntax:
class ClassName
{
... The keyword is the operator.
public:
... The return type of the function is
return-type operator op(params-list) ‘returnType.’
{
The arguments passed to the
//body of the function
...
function are arguments.
} The operator is nothing but the
... symbol that you need to overload.
};
2
Overloading Unary Operator:
#include <iostream> #include <iostream>
using namespace std; using namespace std;
Output:
3
Overloading Binary Operator:
obj1.a + obj2.a: 40
obj1.b + obj2.b: 60
4
Overloading ! Operator
#include <iostream>
using namespace std;
class NotOp {
private:
int a;
bool b;
public:
NotOp() : a(false), b(true) {}
// Overloading the NOT (!) operator
void operator ! () {
a= !a;
b= !b;
}
void out() {
cout<<"Output: "<<endl<< a<<endl<<b;
}
};
int main() {
NotOp obj;
!obj;
obj.out();
return 0;
}
Output:
Output:
1
0