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

Operator Overloading and Data Conversion

The document discusses operator overloading in C++, focusing on both unary and binary operators, and how it enhances code readability and flexibility for user-defined types. It explains the process of overloading operators, the importance of data conversion between basic and user-defined types, and provides examples of implementing these concepts. Additionally, it covers conversion between different classes and the methods used for such conversions.

Uploaded by

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

Operator Overloading and Data Conversion

The document discusses operator overloading in C++, focusing on both unary and binary operators, and how it enhances code readability and flexibility for user-defined types. It explains the process of overloading operators, the importance of data conversion between basic and user-defined types, and provides examples of implementing these concepts. Additionally, it covers conversion between different classes and the methods used for such conversions.

Uploaded by

Rivicca Castillo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Lesson 5: Operator Overloading

• Overloading Unary Operators


• Overloading Binary Operators
• Data Conversion
5.1 Introduction to Operator Overloading
What is Operator Overload?
• One of the most exciting feature of Object-Oriented Programming
• Allows complex code to become intuitive and readable

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)

• After overloading: a = b + c; (now works with custom


objects
Why Use Operator Overloading?
• Provides flexibility and control over user-defined types
• Enhances code readability and simplicity
• Transforms complex operations into clear expressions
Redefining C++ Operators

• Operator overloading lets you redefine the behavior of


operators for your objects

• Create new types of variables and operations

• Extend C++ to fit your program's specific needs


5.2 Overloading Unary Operators

• Unary operators act on a single operand

Example operators: ++, --, and unary minus -

Example using user-define object:


• Instead of c1.inc_count();
• We use ++c1; // using prefix unary operator
Counter Class Example without Overloading

Header file
Counter Class Example

Header file Source file


Counter Class Example

Header file Source file


Counter Class Example

Header file Source file


Counter Class Example

Header file Source file


Example: Overloading the ++ Operator
• Original way: c1.inc_counter();
• After overloading: ++c1;

• The operator Keyword


void operator ++();
Counter Class Example with overloading

Header file
Counter Class Example

Header file Source file


Counter Class Example

Header file Source file


Counter Class Example

Header file Source file


Counter Class Example
Header file
Main file

Source file

Output
The operator Keyword
• Purpose:
• Enables C++ operators to act on user-defined operands
• Syntax Example:
void operator ++ ();

• Return type is void


• Followed by the keyword operator
• Then the operator (++)
• Argument list (empty in this case)
How Overloading Works

• Function call:
• The syntax directs the compiler to call the overloaded function
when the operator is encountered

• E.g., ++c1; will trigger the overloaded ++ function in class


Counter
Distinguishing Overloaded Operators

• How the Compiler Identifies Overloading:


• The compiler looks at the data types and number of
arguments

• Distinguishes between built-in operators and overloaded ones


based on the operand type
Example: Incrementing a Basic vs. User-
Defined Type
• Built-in Data type
• ++intvar; // Uses built-in increment for `int`

• User-Defined Data Type


• ++c1; // Uses overloaded increment for `Counter`
Overloading Binary Operators
English Measurement System:
• Architectural drawings in the United States use feet and inches to
measure distances.
• There are 12 inches in a foot.
• Example: The length of a living room might be expressed as 15’–8”,
meaning 15 feet plus 8 inches.
• The hyphen in such measurements separates feet from inches, not
indicating a negative value.
• This measurement system is part of the English system of
measurement.
• No comparison or judgment is made between the English and metric
systems in this context.
English Measurement System:
Example Exercise:

Suppose you want to create a drawing or architectural program that


uses the English system. It will be convenient to store distances as
two numbers, representing feet and inches.
Header file Source file Example with Overload
Header file Source file Example with Overload
Header file Source file Example with Overload
Header file Source file Example with Overload
Header file Source file Example with Overload
Header file Source file Example with Overload
Data Types Conversion
Data Types Conversion

• C++ converts simple types automatically, like int to float

• User-defined types require manual conversions

• Overloading helps with custom conversions


Data Types Conversion
• The = operator assigns values between variables and objects.
• For basic types, the assignment looks like:
• intvar1 = intvar2;

• User-defined objects of the same type can also be assigned using =.


• Example for user-defined objects: dist3 = dist1 + dist2;
• During assignment, member data is copied from one object to another.
• No special instructions are needed for object assignment; the compiler
handles it automatically.
Data Types Conversion
• The compiler automatically handles assignments between variables of
the same type.
• Conversion becomes complex when variables on both sides of the = are
of different types.
• Basic types often convert automatically, but user-defined types may
require explicit instructions.
• C++ supports conversions between:
• Basic types
• Basic and user-defined types
• Different user-defined types

• C++ allows type conversions for flexibility, though it is a debated


practice in programming.
Conversion Between Basic Type
(Built-in Types)
Conversion Between Basic Type (Built-in Types)
• Basic type conversions occur automatically (implicit conversion).
• Example: intvar = floatvar; converts a float to an int.
• The compiler has built-in routines for many type conversions.
• Implicit conversions are invisible in the code.
• Explicit conversions use the cast operator.
• Example of explicit conversion:
• intvar = static_cast<int>(floatvar);
• Both implicit and explicit conversions use the same built-in
routines.
Conversion User-defined Object
and Basic Types
Conversion User-defined Object and Basic Types

• No built-in routines for conversions between user-defined types


and basic types.
• The compiler relies on what we define for user-defined types.
• We must write custom routines for these conversions.
Conversion User-defined Object and Basic Types

our class Distance.


Conversion User-defined Object and Basic Types
Sample Program.
Sample program of English Measurement System with:
1. Operator Overloading (Unary and Binary):
• ++ (Postfix and prefix)
• +
• -
• >
• ==
2. Data Conversion from Basic to User-defined and vice versa:
• Conversion Operators.
• Conversion Constructors.

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.

• We will be going to convert from Time24 to Time12 using


operator in time24
Time12() Without Conversion (Routine in Source Object)

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.

• We will be going to convert from Time24 to Time12 using


operator in time24
Time12() With Conversion (Routine in Destination Object)

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

2. Conversion using Conversion Constructor:


• Can convert vice versa:
• Link: https://1drv.ms/f/c/599b1f6f16cbbd13/EpIb_cYyJ65OiBqKr4L7ghUBq-
dCek0cYtUqeBCLJlLb6w?e=eGqVaw

You might also like