C++ Lecture 22
C++ Lecture 22
02
LECTURE 22
04
Today’s Agenda
01 Operator Overloading
05
Operator Overloading
In the previous class, we discuss the 4 ways of adding two different objects of the same class and the
following are the calls of the methods
Operator Overloading in C++ is a mechanism using which a programmer can redefine the built-in operators
of C++ language in such a way that these operators can now work upon objects of programmer-defined
classes much in the same way they work upon variables of primitives data types.
In other words, we can say that Operator Overloading increases the domain of operators from variables to
objects.
The most important benefit of Operator Overloading is simplicity in the readability of the call. That is,
function calls which are given using Operator Overloading are much easier to understand and write as
compared to the conventional way of giving function calls
Techniques of Overloading Operators
And we know that the private data members can only be accessed by the member
functions or by the friend functions of the class
Operator Overloading
Since operators will have to access the private data members of the class while working on
objects, so either these operators have to make MEMBER FUNCTIONS or they have to be
made FRIEND FUNCTIONS
1. As members functions:
2. As friend functions:
class Counter
{ void Counter::operator++()
private: {
int count; ++count;
public: }
Counter()
{ int main()
count = 0; {
} Counter C1(10);
Counter(int c) C1.show();// => 10
{ ++C1;//C1.operator++();//This will be converted into this form
count = c; by the compiler during generation of machine code
} C1.show();// => 11
void show() return 0;
{ }.
cout<<count<<endl;
}
void operator++();
};
Output of The Previous Code
Output
10
11
class Counter
{ void Counter::operator++() What should be the
private: {
int count; ++count;
output?
public: }
Counter()
What will be the output? If everything is OK,
{ int main()
count = 0; { then the output should
}
Syntax Error Counter C1(10); be 11 and 11
Counter(int c) Counter C2;
{ C1.show();
count = c; C2.show();
} C2 = ++C1; C2 = C1.operator++();
void show() C1.show();
{ C2.show();
cout<<count<<endl; return 0;
} }
void operator++(); C2 = _;
};
End of Lecture 22
For any queries mail us @: [email protected]
Call us @ : 0755-4271659, 7879165533
Thank you