0% found this document useful (0 votes)
3 views

6721c2b323683OperatorOverloading MakeupLecture 30thoctober2024

Uploaded by

Nouman Mukhtar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

6721c2b323683OperatorOverloading MakeupLecture 30thoctober2024

Uploaded by

Nouman Mukhtar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Operator

Overloading
Little Recap !

• In C++, operator overloading allows us to redefine how operators (like +, -, *, =,


etc.) work with user-defined types (e.g., classes).
• However, this overloading doesn’t happen automatically; you must explicitly
define how an operator should behave for your specific class by creating
operator-overloading functions.
• An operator is overloaded by writing a function that begins with the keyword
operator followed by the operator symbol you want to overload. This function
can be defined as a member function (within the class).
• For example, the function name operator+ would be used to overload the
addition operator (+) for use with objects of a particular class. When operators
are overloaded as member functions, they must be non-static, because they
must be called on an object of the class and operate on that object.

Operators that cannot be overloaded

Example with a little modification:


Another Example
Postfix Notation
• So far we’ve shown the increment operator used only in its prefix
form. ++c1
• What about postfix, where the variable is incremented after its value
is used in the expression? c1++
Dummy
Increment count and return a new Counter parameter
Return a new Counter with the current count, then increment
This overload allows the use of ++c1 (prefix). It first increments count and
then creates a new Counter object with the updated count, which is
returned.

• This overload allows the use of c1++ (postfix).


• The current value of count is returned by creating a new Counter object
(Counter(count++)).
• The count++ expression first uses the current value of count to create the new
Counter object, and after that, it increments count.
• This is the key behavior of postfix increment is that it returns the value before the
increment occurs.
To do practice examples
Code # 1

• Try to implement prefix and postfix decrement operator based


Member function for objects using operator loading concept.

Code # 2

• Try to compare data items of three objects using <= or > operators
based member functions inside a single class code.

You might also like