0% found this document useful (0 votes)
41 views12 pages

Module 9

This document discusses operator overloading in C++. It begins by explaining the difference between operators and functions. Operators typically operate on operands and have predefined meaning, while functions are callable with a name. The document then shows how operator overloading allows defining new behaviors for operators by defining operator functions. Examples shown include overloading operator+ to concatenate strings and change the behavior of addition for an enum type. Operator overloading allows users to customize operator semantics for user-defined types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views12 pages

Module 9

This document discusses operator overloading in C++. It begins by explaining the difference between operators and functions. Operators typically operate on operands and have predefined meaning, while functions are callable with a name. The document then shows how operator overloading allows defining new behaviors for operators by defining operator functions. Examples shown include overloading operator+ to concatenate strings and change the behavior of addition for an enum type. Operator overloading allows users to customize operator semantics for user-defined types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Module 09

Intructors:
Abir Das and
Sourangshu
Module 09: Programming in C++
Bhattacharya
Operator Overloading
Objectives &
Outline

Operators &
Functions
Intructors: Abir Das and Sourangshu Bhattacharya
Operator
Overloading

Examples
Department of Computer Science and Engineering
String
Indian Institute of Technology, Kharagpur
Enum
{abir, sourangshu}@cse.iitkgp.ac.in
Operator
Overloading
Rules
Slides taken from NPTEL course on Programming in C++
Summary
by Prof. Partha Pratim Das

NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 1
Module Objectives

Module 09

Intructors:
Understand the Operator Overloading
Abir Das and
Sourangshu
Bhattacharya

Objectives &
Outline

Operators &
Functions

Operator
Overloading

Examples
String
Enum

Operator
Overloading
Rules

Summary

NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 2
Module Outline

Module 09

Intructors:
Basic Differences between Operators & Functions
Abir Das and
Sourangshu Operator Overloading
Bhattacharya
Examples of Operator Overloading
Objectives &
Outline
operator+ for String & Enum
Operators & Operator Overloading Rules
Functions

Operator
Overloading

Examples
String
Enum

Operator
Overloading
Rules

Summary

NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 3
Operator & Function

Module 09 What is the difference between an operator & a function?


Intructors: unsigned int Multiply(unsigned x, unsigned y) {
Abir Das and
Sourangshu int prod = 0;
Bhattacharya while (y-- > 0) prod += x;
return prod;
Objectives & }
Outline

Operators & int main() {


Functions unsigned int a = 2, b = 3;
Operator
Overloading // Computed by ’*’ operator
Examples unsigned int c = a * b; // c is 6
String
Enum // Computed by Multiply function
Operator unsigned int d = Multiply(a, b); // d is 6
Overloading
Rules
return 0;
Summary }

Same computation by an operator and a function

NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 4
Difference between Operator & Functions

Module 09
Operator Function
Intructors:
Abir Das and
Sourangshu • Usually written in infix nota- • Always written in prefix no-
Bhattacharya
tion tation
Objectives & • Examples: • Examples:
Outline Infix: a + b; a ? b : c; Prefix: max(a, b);
Operators &
Prefix: ++a; qsort(int[], int, int,
Functions Postfix: a++; void (*)(void*, void*));
Operator
• Operates on one or more • Operates on zero or more ar-
Overloading operands, typically up to 3 guments
Examples (Unary, Binary or Ternary)
String
Enum
• Produces one result • Produces up to one result
Operator • Order of operations is de- • Order of application is de-
Overloading
Rules
cided by precedence and asso- cided by depth of nesting
ciativity
Summary
• Operators are pre-defined • Functions can be defined as
needed

NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 5
Operator Functions in C++

Module 09 Introduces a new keyword: operator


Intructors: Every operator is associated with an operator function that
Abir Das and
Sourangshu defines its behavior
Bhattacharya Operator Expression Operator Function
a + b operator+(a, b)
Objectives &
Outline
a = b operator=(a, b)
c = a + b operator=(c, operator+(a, b))
Operators &
Functions
Operator functions are implicit for predefined operators of
Operator
Overloading
built-in types and cannot be redefined
Examples An operator function may have a signature as:
String
Enum
MyType a, b; // An enum or struct
Operator
Overloading MyType operator+(MyType, MyType); // Operator function
Rules

Summary a + b // Calls operator+(a, b)

C++ allows users to define an operator function and overload it

NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 6
Program 09.01: String Concatenation

Module 09 Concatenation by string functions Concatenation operator

Intructors: #include <iostream> #include <iostream>


Abir Das and #include <cstring> #include <cstring>
Sourangshu using namespace std; using namespace std;
Bhattacharya typedef struct _String { char *str; typedef struct _String { char *str; } String;
} String; String operator+(const String& s1, const String& s2)
int main(){ String s;
Objectives & String fName, lName, name; s.str = (char *) malloc(strlen(s1.str) +
Outline fName.str = strdup("Partha "); strlen(s2.str) + 1);
lName.str = strdup("Das" ); strcpy(s.str, s1.str);
Operators & name.str = (char *) malloc( strcat(s.str, s2.str);
Functions strlen(fName.str) + return s;
strlen(lName.str) + 1); }
Operator
strcpy(name.str, fName.str); int main() {
Overloading
strcat(name.str, lName.str); String fName, lName, name;
Examples fName.str = strdup("Partha ");
cout << "First Name: " << lName.str = strdup("Das");
String
fName.str << endl;
Enum
cout << "Last Name: " << name = fName + lName; // Overload operator +
Operator lName.str << endl;
Overloading cout << "Full Name: " << cout << "First Name: " << fName.str << endl;
Rules name.str << endl; cout << "Last Name: " << lName.str << endl;
return 0; cout << "Full Name: " << name.str << endl;
Summary } return 0;
---------- }
First Name: Partha ----------
Last Name: Das First Name: Partha
Full Name: Partha Das Last Name: Das
Full Name: Partha Das
NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 7
Program 09.02: A new semantics for operator+
w/o Overloading + Overloading operator +
Module 09
#include <iostream> #include <iostream>
Intructors: using namespace std; using namespace std;
Abir Das and enum E {C0 = 0, C1 = 1, C2 = 2}; enum E {C0 = 0, C1 = 1, C2 = 2};
Sourangshu
Bhattacharya E operator+(const E& a, const E& b) {
unsigned int uia = a, uib = b;
unsigned int t = (uia + uib) % 3;
Objectives & return (E) t;
Outline }
int main() { int main() {
Operators &
E a = C1, b = C2; E a = C1, b = C2;
Functions
int x = -1; int x = -1;
Operator
Overloading x = a + b; x = a + b;
cout << x << endl; cout << x << endl;
Examples
String return 0; return 0;
Enum
} }
---------- ----------
Operator 3 0
Overloading
Rules • Implicitly converts enum E values to int
• Adds by operator+ of int • operator + is overloaded for enum E
Summary • Result is outside enum E range • Result is a valid enum E value

NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 8
Operator Overloading – Summary of Rules

Module 09
No new operator such as **, <>, or &| can be defined for overloading
Intructors:
Abir Das and Intrinsic properties of the overloaded operator cannot be change
Sourangshu
Bhattacharya Preserves arity
Preserves precedence
Objectives & Preserves associativity
Outline
These operators can be overloaded:
Operators &
Functions [] + - * / % ^ & | ~ ! = += -= *= /= %= ^= &= |=
<< >> >>= <<= == != < > <= >= && || ++ -- , ->* -> ( ) [ ]
Operator
Overloading For unary prefix operators, use: MyType& operator++(MyType& s1)
Examples For unary postfix operators, use: MyType operator++(MyType& s1, int)
String
Enum The operators :: (scope resolution), . (member access), .* (member access
through pointer to member), sizeof, and ?: (ternary conditional) cannot
Operator
Overloading be overloaded
Rules
The overloads of operators &&, ||, and , (comma) lose their special
Summary properties: short-circuit evaluation and sequencing
The overload of operator-> must either return a raw pointer or return an
object (by reference or by value), for which operator-> is in turn overloaded

NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 9
Overloading disallowed for

Module 09 Operator Reason


Intructors:
Abir Das and • dot (.) • The second argument is a name (of the field or
Sourangshu member function), rather than a value
Bhattacharya

• Scope Resolution ( :: ) • It performs a (compile time) scope resolution rather


Objectives &
Outline than an expression evaluation.
Operators &
Functions • Ternary (? :) • overloading expr1 ? expr2 : expr3 would not be
able to guarantee that only one of expr2 and expr3
Operator
Overloading was executed
Examples
String
• sizeof • Sizeof cannot be overloaded because built-in oper-
Enum ations, such as incrementing a pointer into an array
implicitly depends on it
Operator
Overloading
Rules

Summary

NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 10
Do not overload these operators

Module 09 Operator Reason


Intructors:
Abir Das and • && and | | • In evaluation, the second operand is not evaluated
Sourangshu if the result can be deduced solely by evaluating the
Bhattacharya
first operand. However, this evaluation is not possi-
ble for overloaded versions of these operators
Objectives &
Outline
• Comma ( , ) • This operator guarantees that the first operand is
Operators &
Functions evaluated before the second operand. However, if
the comma operator is overloaded, its operand eval-
Operator
Overloading uation depends on C++’s function parameter mech-
anism, which does not guarantee the order of evalu-
Examples
ation
String
Enum
• Ampersand (&) • The address of an object of incomplete type can
Operator
Overloading be taken, but if the complete type of that object is
Rules a class type that declares operator &() as a member
Summary function, then the behavior is undefined

NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 11
Module Summary

Module 09

Intructors:
Introduced operator overloading
Abir Das and
Sourangshu Explained the rules of operator overloading
Bhattacharya

Objectives &
Outline

Operators &
Functions

Operator
Overloading

Examples
String
Enum

Operator
Overloading
Rules

Summary

NPTEL MOOCs Programming in C++ Intructors: Abir Das and Sourangshu Bhattacharya 12

You might also like