Operator Overloading and Data Conversion
Operator Overloading and Data Conversion
Example:
Before: d3.addobjects(d1, d2);
After: d3 = d1 + d2;
What Operators Can be Overloaded?
• Operators to Overload
• Common Operators: +, -, *, /, <=, >=, +=
• Normally: a = b + c; (works with int or float)
Header file
Counter Class Example
Header file
Counter Class Example
Source file
Output
The operator Keyword
• Purpose:
• Enables C++ operators to act on user-defined operands
• Syntax Example:
void operator ++ ();
• Function call:
• The syntax directs the compiler to call the overloaded function
when the operator is encountered
Link: https://1drv.ms/f/c/599b1f6f16cbbd13/EkpPjppxB3hKo-117YiiCHwBXBBad5YkV6Z5wb02iCbWIQ?e=fVh54r
Conversion of Objects of
Different Classes
Conversion of Objects of Different Classes
• Conversions Between Classes: Converting objects between
different user-defined types.
• Methods for Conversion:
• One-Argument Constructor (in Destination Class): Initializes destination
object from source
• Conversion Operator (in Source Class): Converts source object to
destination type
• Example: objecta = objectb;
• objecta = Destination (class A), objectb = Source (class B).
• Decision Factor: Location of conversion routine based on source
vs. destination class
Two Kinds of Time
• Two Kinds of Time Measurement:
• Civilian Time (12-hour format): Hours (1-12), minutes, "a.m." or "p.m.“
• Military Time (24-hour format): Hours (00-23), minutes, seconds.
• Classes for Conversion:
• Time12 class for 12-hour time (e.g., digital clocks, flight displays)
• Time24 class for 24-hour time (e.g., precise applications like navigation)
• Purpose: Convert between two time representations.
12-Hour and 24-Hour Time
Routine in Source Object
• When the conversion routine is in the source class , it is
commonly implemented as a conversion operator.
Time24()
Time12() With Conversion (Routine in Source Object)
Time24()
Conversion
Operator
Routine in Destination Object
• When the conversion routine is in the destination class , it
is commonly implemented as a conversion constructor.
Conversion
constructor
Time24()
NOTE!
So far in our Time Conversion (Time12 and Time24), we
have managed to convert from Time24 to Time12, but not
vice versa. You can explore the program to add a conversion
from Time12 to Time24.
Sample Program.
Sample program of Conversion of objects of different classes
Class Celsius and Class Fahrenheit:
1. Conversion using Conversion Operator:
• Can convert vice versa:
• Link: https://1drv.ms/f/c/599b1f6f16cbbd13/EmNEteNWA0JBgtZA_9Iz-
qQBh_YGgnT1O914RLMp-XOROA?e=48mkfP