Module 09
Module 09
L
Partha Pratim
Das
Programming in Modern C++
E
Objectives &
Outline
Module M09: Operator Overloading
T
Operators &
Functions
Difference
P
Operator
Functions in
Partha Pratim Das
N
C++
Operator
Overloading
Department of Computer Science and Engineering
Advantages and
Disadvantages Indian Institute of Technology, Kharagpur
Examples
String
[email protected]
Enum
Rules
All url’s in this module have been accessed in September, 2021 and found to be functional
Restrictions
Module Summary
Module M09
L
Partha Pratim
Das
• Identified the necessity of function overloading
E
Objectives &
Outline • Introduced static Polymorphism and discussed examples and restrictions
T
Operators &
Functions • Discussed an outline for Overload resolution
Difference
P
Operator
• Discussed the mix of default Parameters and function overloading
Functions in
N
C++
Operator
Overloading
Advantages and
Disadvantages
Examples
String
Enum
Rules
Restrictions
Module Summary
Module M09
L
Partha Pratim
Das
E
Objectives &
Outline
T
Operators &
Functions
Difference
P
Operator
Functions in
N
C++
Operator
Overloading
Advantages and
Disadvantages
Examples
String
Enum
Rules
Restrictions
Module Summary
Module M09
L
Partha Pratim
Das
Difference
E
Objectives &
Outline
2 Operator Functions in C++
T
Operators &
Functions
Difference 3 Operator Overloading
P
Operator Advantages and Disadvantages
Functions in
N
C++
Operator
4 Examples of Operator Overloading
Overloading
Advantages and
String: Concatenation
Disadvantages
Enum: Changing the meaning of operator+
Examples
String
Enum
5 Operator Overloading Rules
Rules
Restrictions
6 Operator Overloading Restrictions
Module Summary
7 Module Summary
Programming in Modern C++ Partha Pratim Das M09.4
Operators and functions
Module M09
L
Partha Pratim
Das
E
Objectives &
Outline
T
Operators &
Functions
Difference
P
Operator
Functions in
N
C++
Operator
Overloading
Advantages and
Disadvantages
Examples
String
Enum
Operators and functions
Rules
Restrictions
Module Summary
Module M09
L
Partha Pratim
Das
unsigned int Multiply(unsigned x, unsigned y) {
E
Objectives & int prod = 0;
Outline while (y-- > 0) prod += x;
return prod;
T
Operators &
Functions }
Difference
P
Operator
int main() {
Functions in unsigned int a = 2, b = 3;
N
C++
L
Partha Pratim
Das
• Usually written in infix notation - at times • Always written in prefix notation
in prefix or postfix
E
Objectives &
Outline
• Examples: • Examples:
T
Operators &
Functions
// Operator in-between operands
Difference
P
Infix: a + b; a ? b : c;
Operator
Functions in // Operator before operands // Operator before operands
N
C++ Prefix: ++a; Prefix: max(a, b);
Operator // Operator after operands qsort(int[], int, int,
Overloading void (*)(void*, void*));
Advantages and
Postfix: a++;
Disadvantages
Module M09
L
Partha Pratim
Das
E
Objectives &
Outline
T
Operators &
Functions
Difference
P
Operator
Functions in
N
C++
Operator
Overloading
Advantages and
Disadvantages
Examples
String
Enum
Operator Functions in C++
Rules
Restrictions
Module Summary
Module M09
• C++ introduces a new keyword: operator
• Every operator is associated with an operator function that defines its behavior
L
Partha Pratim
Das
E
Objectives & Operator Expression Operator Function
Outline
a + b operator+(a, b)
T
Operators &
Functions a = b operator=(a, b)
Difference
operator=(c, operator+(a, b))
P
c = a + b
Operator
Functions in
N
C++
• Operator functions are implicit for predefined operators of built-in types and cannot be
Operator
Overloading redefined
Advantages and
Disadvantages • An operator function may have a signature as:
Examples MyType a, b; // An enum or struct
String
Enum
MyType operator+(MyType, MyType); // Operator function
Rules
Module M09
L
Partha Pratim
Das
E
Objectives &
Outline
T
Operators &
Functions
Difference
P
Operator
Functions in
N
C++
Operator
Overloading
Advantages and
Disadvantages
Examples
String
Enum
Operator Overloading
Rules
Restrictions
Module Summary
Module M09
L
Partha Pratim
Das
polymorphism, where different operators have different implementations depending on
E
Objectives &
Outline
their arguments
• Operator overloading is generally defined by a programming language, For example, in
T
Operators &
Functions
Difference C (and in C++), for operator/, we have:
P
Operator
Functions in Integer Division Floating Point Division
N
C++
Operator
Overloading int i = 5, j = 2; double i = 5, j = 2;
Advantages and
Disadvantages int k = i / j; // k = 2 double k = i / j; // k = 2.5
Examples
String
Enum
Rules
• C does not allow programmers to overload its operators
Restrictions • C++ allows programmers to overload its operators by using operator functions
Module Summary
Module M09
• Advantages:
L
Partha Pratim
Das ◦ Operator overloading is syntactic sugar, and is used because it allows programming
using notation nearer to the target domain
E
Objectives &
Outline
◦ It also allows user-defined types a similar level of syntactic support as types built
T
Operators &
Functions into a language
Difference
◦ It is common in scientific computing, where it allows computing representations of
P
Operator
Functions in mathematical objects to be manipulated with the same syntax as on paper
N
C++
◦ For example, if we build a Complex type in C and a, b and c are variables of
Operator
Overloading Complex type, we need to code an expression
Advantages and
Disadvantages a + b * c
Examples
String
using functions to add and multiply Complex value as
Enum
Add(a, Multiply(b, c))
Rules
Restrictions
which is clumsy and non-intuitive
Module Summary ◦ Using operator overloading we can write the expression with operators without
having to use the functions
Programming in Modern C++ Partha Pratim Das M09.12
Operator Overloading: Advantages and Disadvantages
Module M09
• Disadvantages
L
Partha Pratim
Das ◦ Operator overloading allows programmers to reassign the semantics of operators
depending on the types of their operands. For example, for int a, b, an expression
E
Objectives &
Outline
a << b shifts the bits in the variable a left by b, whereas cout << a << b outputs
T
Operators &
Functions values of a and b to standard output (cout)
Difference
◦ As operator overloading allows the programmer to change the usual semantics of an
P
Operator
Functions in operator, it is a good practice to use operator overloading with care to maintain the
N
C++
Semantic Congruity
Operator
Overloading ◦ With operator overloading certain rules from mathematics can be wrongly expected
Advantages and
Disadvantages or unintentionally assumed. For example, the commutativity of operator+ (that is,
Examples a + b == b + a) is not preserved when we overload it to mean string
String
Enum concatenation as
Rules "run" + "time" = "runtime" 6= "timerun" = "time" + "run"
Restrictions
Of course, mathematics too has such deviations as multiplication is commutative for
Module Summary
real and complex numbers but not commutative in matrix multiplication
Programming in Modern C++ Partha Pratim Das M09.13
Examples of Operator Overloading
Module M09
L
Partha Pratim
Das
E
Objectives &
Outline
T
Operators &
Functions
Difference
P
Operator
Functions in
N
C++
Operator
Overloading
Advantages and
Disadvantages
Examples
String
Enum
Examples of Operator Overloading
Rules
Restrictions
Module Summary
L
Partha Pratim #include <iostream> #include <iostream>
Das #include <cstring> #include <cstring>
using namespace std; using namespace std;
E
Objectives &
Outline
typedef struct _String { char *str; } String; typedef struct _String { char *str; } String;
int main() { String fName, lName, name; String operator+(const String& s1, const String& s2) {
T
Operators & fName.str = strdup("Partha "); String s;
Functions
Difference
lName.str = strdup("Das" ); s.str = (char *) malloc(strlen(s1.str) +
P
name.str = (char *) malloc( // Allocation strlen(s2.str) + 1); // Allocation
Operator strlen(fName.str) + strcpy(s.str, s1.str); strcat(s.str, s2.str);
Functions in
strlen(lName.str) + 1); return s;
N
C++
strcpy(name.str, fName.str); }
Operator
Overloading
strcat(name.str, lName.str); int main() { String fName, lName, name;
Advantages and
cout << "First Name: " << fName.str = strdup("Partha ");
Disadvantages fName.str << endl; lName.str = strdup("Das");
Examples cout << "Last Name: " << name = fName + lName; // Overloaded operator +
String lName.str << endl; cout << "First Name: " << fName.str << endl;
Enum cout << "Full Name: " << cout << "Last Name: " << lName.str << endl;
name.str << endl; cout << "Full Name: " << name.str << endl;
Rules
} }
Restrictions ---------- ----------
Module Summary First Name: Partha First Name: Partha
Last Name: Das Last Name: Das
Full Name: Partha Das Full Name: Partha Das
Programming in Modern C++ Partha Pratim Das M09.15
Program 09.02: A new semantics for operator+
L
Partha Pratim #include <iostream> #include <iostream>
Das using namespace std; using namespace std;
enum E { C0 = 0, C1 = 1, C2 = 2 }; enum E { C0 = 0, C1 = 1, C2 = 2 };
E
Objectives &
Outline
E operator+(const E& a, const E& b) { // Overloaded operator +
T
Operators & unsigned int uia = a, uib = b;
Functions
Difference
unsigned int t = (uia + uib) % 3; // Redefined addition
P
return (E) t;
Operator }
Functions in
int main() { E a = C1, b = C2; int main() { E a = C1, b = C2;
N
C++
int x = -1; int x = -1;
Operator
Overloading
Advantages and
x = a + b; // operator + for int x = a + b; // Overloaded operator + for enum E
Disadvantages cout << x << endl; cout << x << endl;
Examples } }
String ---------- ----------
Enum 3 0
Rules
Module M09
L
Partha Pratim
Das
E
Objectives &
Outline
T
Operators &
Functions
Difference
P
Operator
Functions in
N
C++
Operator
Overloading
Advantages and
Disadvantages
Examples
String
Enum
Operator Overloading Rules
Rules
Restrictions
Module Summary
Module M09 • No new operator such as operators** or operators<> can be defined for overloading
• Intrinsic properties of the overloaded operator cannot be changed
L
Partha Pratim
Das
◦ Preserves arity
E
Objectives &
Outline
◦ Preserves precedence
◦ Preserves associativity
T
Operators &
Functions
Difference
• These operators can be overloaded:
P
Operator [] + - * / % ^ & | ~ ! = += -= *= /= %= ^= &= |=
Functions in
<< >> >>= <<= == != < > <= >= && || ++ -- , ->* -> ( ) [ ]
N
C++
Operator
Overloading
• For unary prefix operators, use: MyType& operator++(MyType& s1)
Advantages and
Disadvantages
• For unary postfix operators, use: MyType operator++(MyType& s1, int)
Examples
• The operators:: (scope resolution), operator. (member access), operator.* (member
String access through pointer to member), operator sizeof, and operator?: (ternary conditional)
Enum
cannot be overloaded
Rules
• The overloads of operators&&, operator||, and operator, (comma) lose their special
Restrictions
properties: short-circuit evaluation and sequencing
Module Summary
• The overload of operators-> must either return a raw pointer or return an object (by
reference or by value), for which operators-> is in turn overloaded
Programming in Modern C++ Partha Pratim Das M09.18
Operator Overloading Restrictions
Module M09
L
Partha Pratim
Das
E
Objectives &
Outline
T
Operators &
Functions
Difference
P
Operator
Functions in
N
C++
Operator
Overloading
Advantages and
Disadvantages
Examples
String
Enum
Operator Overloading Restrictions
Rules
Restrictions
Module Summary
Module M09
operator Reason
dot (.) It will raise question whether it is for object reference or overloading
L
Partha Pratim
Das Scope It performs a (compile time) scope resolution rather than an expression
Resolution evaluation
E
Objectives &
Outline (::)
T
Operators &
Functions
Ternary (?:) Overloading expr1? expr2: expr3 would not guarantee that only one
Difference of expr2 and expr3 was executed
P
Operator sizeof Operator sizeof cannot be overloaded because built-in operations, such
Functions in
as incrementing a pointer into an array implicitly depends on it
N
C++
Operator && and || In evaluation, the second operand is not evaluated if the result can be
Overloading
Advantages and
deduced solely by evaluating the first operand. However, this evaluation is
Disadvantages
not possible for overloaded versions of these operators
Examples
String
Comma (,) This operator guarantees that the first operand is evaluated before the
Enum second operand. However, if the comma operator is overloaded, its operand
Rules evaluation depends on C++’s function parameter mechanism, which does
Restrictions not guarantee the order of evaluation
Module Summary Ampersand The address of an object of incomplete type can be taken, but if the
(&) complete type of that object is a class type that declares operator&() as
Programming in Modern C++ a member function, then the behavior
Partha Pratimis
Dasundefined M09.20
Module Summary
Module M09
L
Partha Pratim
Das
• Explained the rules of operator overloading
E
Objectives &
Outline
T
Operators &
Functions
Difference
P
Operator
Functions in
N
C++
Operator
Overloading
Advantages and
Disadvantages
Examples
String
Enum
Rules
Restrictions
Module Summary