You are on page 1of 142

Module M06

L
Partha Pratim
Das
Programming in Modern C++

E
Weekly Recap

Objectives & Module M06: Constants and Inline Functions

T
Outline

cv-qualifier:

P
const &
volatile
const
Partha Pratim Das

N
Advantages
Pointers
C-String
Department of Computer Science and Engineering
volatile
Indian Institute of Technology, Kharagpur
inline functions
Macros ppd@cse.iitkgp.ac.in
Pitfalls
inline
Comparison
All url’s in this module have been accessed in September, 2021 and found to be functional
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.1


Weekly Recap

Module M06

• Understood the importance and ease of C++ in programming

L
Partha Pratim
Das
• KYC - Pre-requisites, Outline, Evaluation and Textbooks and References

E
Weekly Recap

Objectives &
• Understood some fundamental differences between C & C++:

T
Outline
◦ IO, Variable declaration, and Loops
cv-qualifier:
◦ Arrays and Strings

P
const &
volatile
const ◦ Sorting and Searching

N
Advantages
Pointers
◦ Stack and Common Containers in C++
C-String ◦ Various Standard Library in C and in C++
volatile

inline functions
Macros
Pitfalls
inline
Comparison
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.2


Module Objectives

Module M06

• Understand const in C++ and contrast with Manifest Constants

L
Partha Pratim
Das
• Understand inline in C++ and contrast with Macros

E
Weekly Recap

Objectives &

T
Outline

cv-qualifier:

P
const &
volatile
const

N
Advantages
Pointers
C-String
volatile

inline functions
Macros
Pitfalls
inline
Comparison
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.3


Module Outline

Module M06

1 Weekly Recap

L
Partha Pratim
Das

2 cv-qualifier: const & volatile

E
Weekly Recap

Objectives & Notion of const

T
Outline
Advantages of const
cv-qualifier:
const and pointer

P
const &
volatile
C-String
const
Notion of volatile

N
Advantages
Pointers
C-String
volatile
3 inline functions
inline functions Macros with Params in C
Macros Pitfalls of Macros
Pitfalls
inline Notion of inline
Comparison Comparison of Macros and inline Functions
Limitations Limitations of inline Functions
Module Summary
4 Module Summary
Programming in Modern C++ Partha Pratim Das M06.4
const-ness and cv-qualifier

Module M06

L
Partha Pratim
Das

E
Weekly Recap

Objectives &

T
Outline

cv-qualifier:

P
const &
volatile
const

N
Advantages
Pointers
C-String
volatile

inline functions
Macros
Pitfalls
inline
const-ness and cv-qualifier
Comparison
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.5


Program 06.01: Manifest constants in C / C++

Module M06 • Manifest constants are defined by #define


• Manifest constants are replaced by CPP (C Pre-Processor). Check Tutorial on C Preprocessor (CPP)

L
Partha Pratim
Das Source Program Program after CPP

E
Weekly Recap #include <iostream> // Contents of <iostream> header replaced by CPP
Objectives & #include <cmath> // Contents of <cmath> header replaced by CPP

T
Outline using namespace std; using namespace std;
cv-qualifier:
#define TWO 2 // Manifest const // #define of TWO consumed by CPP

P
const &
volatile #define PI 4.0*atan(1.0) // Const expr. // #define of PI consumed by CPP
const

N
Advantages
int main() { int r = 10; int main() { int r = 10;
Pointers
double peri = TWO * PI * r; double peri = 2 * 4.0*atan(1.0) * r; // By CPP
C-String
cout << "Perimeter = " << peri << endl; cout << "Perimeter = " << peri << endl;
volatile
} }
inline functions
Macros
Pitfalls
Perimeter = 62.8319 Perimeter = 62.8319
inline
Comparison
Limitations
• TWO is a manifest constant • CPP replaces the token TWO by 2
Module Summary • PI is a manifest constant as macro • CPP replaces the token PI by 4.0*atan(1.0) and evaluates
• TWO & PI look like variables • Compiler sees them as constants
• TWO * PI = 6.28319 by constant folding of compiler
Programming in Modern C++ Partha Pratim Das M06.6
Notion of const-ness

Module M06
• The value of a const variable cannot be changed after definition
const int n = 10; // n is an int type variable with value 10. n is a constant

L
Partha Pratim
Das ...
n = 5; // Is a compilation error as n cannot be changed

E
Weekly Recap ...
Objectives &
int m;

T
Outline int *p = 0;
p = &m; // Hold m by pointer p
cv-qualifier:
*p = 7; // Change m by p; m is now 7

P
const &
volatile ...
const p = &n; // Is a compilation error as n may be changed by *p = 5;

N
Advantages
Pointers
• Naturally, a const variable must be initialized when defined
C-String
const int n; // Is a compilation error as n must be initialized
volatile

inline functions
• A variable of any data type can be declared as const
Macros typedef struct _Complex {
Pitfalls double re;
inline double im;
Comparison
} Complex;
Limitations
const Complex c = {2.3, 7.5}; // c is a Complex type variable
Module Summary // It is initialized with c.re = 2.3 and c.im = 7.5. c is a constant
...
c.re = 3.5; // Is a compilation error as no part of c can be changed
Programming in Modern C++ Partha Pratim Das M06.7
Program 06.02: Compare #define and const
Using #define Using const
Module M06
#include <iostream> #include <iostream>

L
Partha Pratim
Das #include <cmath> #include <cmath>
using namespace std; using namespace std;

E
Weekly Recap

Objectives &
#define TWO 2 const int TWO = 2;

T
Outline #define PI 4.0*atan(1.0) const double PI = 4.0*atan(1.0);
cv-qualifier:
int main() { int r = 10; int main() { int r = 10;

P
const &
volatile // Replace by CPP // No replacement by CPP
const double peri = 2 * 4.0*atan(1.0) * r; double peri = TWO * PI * r;

N
Advantages cout << "Perimeter = " << peri << endl; cout << "Perimeter = " << peri << endl;
Pointers
} }
C-String
volatile

inline functions Perimeter = 62.8319 Perimeter = 62.8319


Macros
Pitfalls
inline
• TWO is a manifest constant • TWO is a const variable initialized to 2
Comparison
• PI is a manifest constant • PI is a const variable initialized to 4.0*atan(1.0)
Limitations
• TWO & PI look like variables • TWO & PI are variables
Module Summary • Types of TWO & PI may be indeterminate • Type of TWO is const int
• TWO * PI = 6.28319 by constant folding of compiler • Type of PI is const double

Programming in Modern C++ Partha Pratim Das M06.8


Advantages of const

Module M06
• Natural Constants like π, e, Φ (Golden Ratio) etc. can be compactly defined and used

L
Partha Pratim
Das
const double pi = 4.0*atan(1.0); // pi = 3.14159
const double e = exp(1.0); // e = 2.71828
const double phi = (sqrt(5.0) + 1) / 2.0; // phi = 1.61803

E
Weekly Recap

Objectives &
const int TRUE = 1; // Truth values

T
Outline
const int FALSE = 0;
cv-qualifier:

P
const &
volatile const int null = 0; // null value
const
Note: NULL is a manifest constant in C/C++ set to 0

N
Advantages
Pointers
C-String • Program Constants like number of elements, array size etc. can be defined at one place (at
volatile times in a header) and used all over the program
inline functions
const int nArraySize = 100;
Macros
const int nElements = 10;
Pitfalls
inline
Comparison
int main() {
Limitations int A[nArraySize]; // Array size
for (int i = 0; i < nElements; ++i) // Number of elements
Module Summary
A[i] = i * i;
}

Programming in Modern C++ Partha Pratim Das M06.9


Advantages of const

Module M06
• Prefer const over #define

L
Partha Pratim
Das
Using #define Using const

E
Weekly Recap

Objectives &
Manifest Constant Constant Variable

T
Outline

cv-qualifier:
• •

P
const &
volatile
Is not type safe Has its type
const • Replaced textually by CPP • Visible to the compiler

N
Advantages
Pointers
• Cannot be watched in debugger • Can be watched in debugger
C-String • Evaluated as many times as replaced • Evaluated only on initialization
volatile

inline functions
Macros
Pitfalls
inline
Comparison
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.10


const and Pointers

Module M06

• const-ness can be used with Pointers in one of the two ways:

L
Partha Pratim
Das
◦ Pointer to Constant data where the pointee (pointed data) cannot be changed

E
Weekly Recap
◦ Constant Pointer where the pointer (address) cannot be changed
Objectives &

T
Outline • Consider usual pointer-pointee computation (without const):
cv-qualifier: int m = 4;

P
const &
volatile int n = 5;
const int * p = &n; // p points to n. *p is 5

N
Advantages ...
Pointers n = 6; // n and *p are 6 now
C-String *p = 7; // n and *p are 7 now. POINTEE changes
volatile ...
inline functions p = &m; // p points to m. *p is 4. POINTER changes
Macros *p = 8; // m and *p are 8 now. n is 7. POINTEE changes
Pitfalls
inline
Comparison
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.11


const and Pointers: Pointer to Constant data

Module M06
Consider pointed data

L
Partha Pratim
Das
int m = 4;
const int n = 5;

E
Weekly Recap const int * p = &n;
...
Objectives &
n = 6; // Error: n is constant and cannot be changed

T
Outline
*p = 7; // Error: p points to a constant data (n) that cannot be changed
cv-qualifier: p = &m; // Okay

P
const &
volatile *p = 8; // Error: p points to a constant data. Its pointee cannot be changed
const Interestingly,

N
Advantages
Pointers int n = 5;
C-String const int * p = &n;
volatile ...
inline functions n = 6; // Okay
Macros *p = 6; // Error: p points to a constant data (n) that cannot be changed
Pitfalls
inline
Finally,
Comparison const int n = 5;
Limitations int *p = &n; // Error: If this were allowed, we would be able to change constant n
Module Summary ...
n = 6; // Error: n is constant and cannot be changed
*p = 6; // Would have been okay, if declaration of p were valid
Programming in Modern C++ Partha Pratim Das M06.12
const and Pointers: Constant Pointer

Module M06
Consider pointer
int m = 4, n = 5;

L
Partha Pratim
Das
int * const p = &n;
...

E
Weekly Recap n = 6; // Okay
*p = 7; // Okay. Both n and *p are 7 now
Objectives &
...

T
Outline
p = &m; // Error: p is a constant pointer and cannot be changed
cv-qualifier:
By extension, both can be const

P
const &
volatile
const const int m = 4;

N
Advantages const int n = 5;
Pointers const int * const p = &n;
C-String ...
volatile n = 6; // Error: n is constant and cannot be changed
inline functions *p = 7; // Error: p points to a constant data (n) that cannot be changed
Macros ...
Pitfalls p = &m; // Error: p is a constant pointer and cannot be changed
inline
Comparison
Finally, to decide on const-ness, draw a mental line through *
Limitations int n = 5;
Module Summary int * p = &n; // non-const-Pointer to non-const-Pointee
const int * p = &n; // non-const-Pointer to const-Pointee
int * const p = &n; // const-Pointer to non-const-Pointee
const int * const p = &n; // const-Pointer to const-Pointee
Programming in Modern C++ Partha Pratim Das M06.13
const and Pointers: The case of C-string

Module M06 Consider the example:


char * str = strdup("IIT, Kharagpur");

L
Partha Pratim
Das str[0] = ’N’; // Edit the name
cout << str << endl;

E
Weekly Recap str = strdup("JIT, Kharagpur"); // Change the name
Objectives & cout << str << endl;

T
Outline
Output is:
cv-qualifier:
NIT, Kharagpur

P
const &
volatile JIT, Kharagpur
const
To stop editing the name:

N
Advantages
Pointers const char * str = strdup("IIT, Kharagpur");
C-String str[0] = ’N’; // Error: Cannot Edit the name
volatile str = strdup("JIT, Kharagpur"); // Change the name
inline functions
Macros
To stop changing the name:
Pitfalls char * const str = strdup("IIT, Kharagpur");
inline str[0] = ’N’; // Edit the name
Comparison str = strdup("JIT, Kharagpur"); // Error: Cannot Change the name
Limitations
To stop both:
Module Summary
const char * const str = strdup("IIT, Kharagpur");
str[0] = ’N’; // Error: Cannot Edit the name
str = strdup("JIT, Kharagpur"); // Error: Cannot Change the name
Programming in Modern C++ Partha Pratim Das M06.14
Notion of volatile

Module M06

• Variable Read-Write

L
Partha Pratim
Das
◦ The value of a variable can be read and / or assigned at any point of time

E
Weekly Recap
◦ The value assigned to a variable does not change till a next assignment is made
Objectives &
(value is persistent)

T
Outline

cv-qualifier:
• const

P
const &
volatile
const ◦ The value of a const variable can be set only at initialization – cannot be changed

N
Advantages
Pointers
afterwards
C-String
volatile
• volatile
inline functions ◦ In contrast, the value of a volatile variable may be different every time it is read
Macros
Pitfalls
– even if no assignment has been made to it
inline ◦ A variable is taken as volatile if it can be changed by hardware, the kernel,
Comparison
Limitations
another thread etc.
Module Summary • cv-qualifier: A declaration may be prefixed with a qualifier – const or volatile

Programming in Modern C++ Partha Pratim Das M06.15


Using volatile

Module M06 Consider:


static int i;

L
Partha Pratim
Das void fun(void) {
i = 0;

E
Weekly Recap while (i != 100);
Objectives & }

T
Outline
This is an infinite loop! Hence the compiler should optimize as:
cv-qualifier:

P
const & static int i;
volatile void fun(void) {
const i = 0;

N
Advantages
while (1); // Compiler optimizes
Pointers
}
C-String
volatile Now qualify i as volatile:
inline functions static volatile int i;
Macros
void fun(void) {
Pitfalls
i = 0;
inline
Comparison
while (i != 100); // Compiler does not optimize
Limitations
}
Module Summary
Being volatile, i can be changed by hardware anytime. It waits till the value becomes 100
(possibly some hardware writes to a port).
Programming in Modern C++ Partha Pratim Das M06.16
inline functions

Module M06

L
Partha Pratim
Das

E
Weekly Recap

Objectives &

T
Outline

cv-qualifier:

P
const &
volatile
const

N
Advantages
Pointers
C-String
volatile

inline functions
Macros
Pitfalls
inline
inline functions
Comparison
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.17


Program 06.03: Macros with Parameters

Module M06
• Macros with Parameters are defined by #define
• Macros with Parameters are replaced by CPP

L
Partha Pratim
Das
Source Program Program after CPP

E
Weekly Recap

Objectives & #include <iostream> #include <iostream> // Header replaced by CPP

T
Outline using namespace std; using namespace std;
cv-qualifier:
#define SQUARE(x) x * x // #define of SQUARE(x) consumed by CPP

P
const &
volatile
const int main() { int main() {

N
Advantages int a = 3, b; int a = 3, b;
Pointers
C-String
b = SQUARE(a); b = a * a; // Replaced by CPP
volatile

inline functions cout << "Square = " << b << endl; cout << "Square = " << b << endl;
Macros } }
Pitfalls
inline
Comparison
Square = 9 Square = 9
Limitations

Module Summary
• SQUARE(x) is a macro with one param • CPP replaces the SQUARE(x) substituting x with a
• SQUARE(x) looks like a function • Compiler does not see it as function
Programming in Modern C++ Partha Pratim Das M06.18
Pitfalls of macros

Module M06 Consider the example:


#include <iostream>

L
Partha Pratim
Das using namespace std;

E
Weekly Recap #define SQUARE(x) x * x
Objectives &

T
Outline int main() {
cv-qualifier: int a = 3, b;

P
const &
volatile b = SQUARE(a + 1); // Error: Wrong macro expansion
const

N
Advantages
cout << "Square = " << b << endl;
Pointers
}
C-String
volatile Output is 7 in stead of 16 as expected. On the expansion line it gets:
inline functions b = a + 1 * a + 1;
Macros
Pitfalls To fix:
inline
Comparison
#define SQUARE(x) (x) * (x)
Limitations Now:
Module Summary
b = (a + 1) * (a + 1);

Programming in Modern C++ Partha Pratim Das M06.19


Pitfalls of macros

Module M06 Continuing ...


#include <iostream>

L
Partha Pratim
Das using namespace std;

E
Weekly Recap #define SQUARE(x) (x) * (x)
Objectives &

T
Outline int main() {
cv-qualifier: int a = 3, b;

P
const &
volatile b = SQUARE(++a);
const

N
Advantages
cout << "Square = " << b << endl;
Pointers
}
C-String
volatile

inline functions Output is 25 in stead of 16 as expected. On the expansion line it gets:


Macros
b = (++a) * (++a);
Pitfalls
inline
Comparison
and a is incremented twice before being used! There is no easy fix.
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.20


inline Function

Module M06

• An inline function is just a function like any other

L
Partha Pratim
Das
• The function prototype is preceded by the keyword inline

E
Weekly Recap

Objectives &
• An inline function is expanded (inlined) at the site of its call and the overhead of

T
Outline
passing parameters between caller and callee (or called) functions is avoided
cv-qualifier:

P
const &
volatile
const

N
Advantages
Pointers
C-String
volatile

inline functions
Macros
Pitfalls
inline
Comparison
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.21


Program 06.04: Macros as inline Functions

Module M06 • Define the function


• Prefix function header with inline

L
Partha Pratim
Das
• Compile function body and function call together

E
Weekly Recap Using macro Using inline
Objectives &

T
Outline #include <iostream> #include <iostream>
cv-qualifier: using namespace std; using namespace std;
inline int SQUARE(int x) { return x * x; }

P
const & #define SQUARE(x) x * x
volatile int main() { int main() {
const int a = 3, b; int a = 3, b;

N
Advantages
b = SQUARE(a); b = SQUARE(a);
Pointers
cout << "Square = " << b << endl; cout << "Square = " << b << endl;
C-String
volatile
} }
inline functions
Macros
Square = 9 Square = 9
Pitfalls
inline
Comparison
Limitations
• SQUARE(x) is a macro with one param • SQUARE(x) is a function with one param
• Macro SQUARE(x) is efficient • inline SQUARE(x) is equally efficient
Module Summary
• SQUARE(a + 1) fails • SQUARE(a + 1) works
• SQUARE(++a) fails • SQUARE(++a) works
• SQUARE(++a) does not check type • SQUARE(++a) checks type
Programming in Modern C++ Partha Pratim Das M06.22
Macros & inline Functions: Compare and Contrast

Module M06
Macros inline Functions

L
Partha Pratim
Das

• Expanded at the place of calls • Expanded at the place of calls

E
Weekly Recap

Objectives & • Efficient in execution • Efficient in execution

T
Outline
• Code bloats • Code bloats
cv-qualifier:
• Has syntactic and semantic pitfalls • No pitfall

P
const &
volatile
const • Type checking for parameters is not done • Type checking for parameters is robust

N
Advantages
• Helps to write max / swap for all types • Needs template to support all types
Pointers
C-String • Errors are not checked during compilation • Errors are checked during compilation
volatile
• Not available to debugger • Available to debugger in DEBUG build
inline functions
Macros
Pitfalls
inline
Comparison
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.23


Limitations of Function inlineing

Module M06

• inlineing is a directive – compiler may not inline functions with large body

L
Partha Pratim
Das
• inline functions may not be recursive

E
Weekly Recap

Objectives &
• Function body is needed for inlineing at the time of function call. Hence,

T
Outline
implementation hiding is not possible. Implement inline functions in header files
cv-qualifier:
• inline functions must not have two different definitions

P
const &
volatile
const

N
Advantages
Pointers
C-String
volatile

inline functions
Macros
Pitfalls
inline
Comparison
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.24


Module Summary

Module M06

• Revisited manifest constants from C

L
Partha Pratim
Das
• Understood const-ness, its use and advantages over manifest constants, and its

E
Weekly Recap
interplay with pointers
Objectives &

T
Outline
• Understood the notion and use of volatile data
cv-qualifier:
• Revisited macros with parameters from C

P
const &
volatile
const
• Understood inline functions, their advantages over macros, and their limitations

N
Advantages
Pointers
C-String
volatile

inline functions
Macros
Pitfalls
inline
Comparison
Limitations

Module Summary

Programming in Modern C++ Partha Pratim Das M06.25


Module M07

L
Partha Pratim
Das
Programming in Modern C++

E
Objectives &
Outlines
Module M07: Reference & Pointer

T
Reference
Pitfalls

P
Call-by-Reference
Swap in C
Swap in C++ Partha Pratim Das

N
const Reference
Parameter

Return-by- Department of Computer Science and Engineering


Reference Indian Institute of Technology, Kharagpur
Pitfalls

I/O Params of a ppd@cse.iitkgp.ac.in


Function

Recommended
Mechanisms All url’s in this module have been accessed in September, 2021 and found to be functional
References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.1


Module Recap

Module M07

• Revisited manifest constants from C

L
Partha Pratim
Das
• Understood const-ness, its use and advantages over manifest constants, and its

E
Objectives &
Outlines interplay with pointers

T
Reference
Pitfalls
• Understood the notion and use of volatile data
• Revisited macros with parameters from C

P
Call-by-Reference
Swap in C
Swap in C++ • Understood inline functions, their advantages over macros, and their limitations

N
const Reference
Parameter

Return-by-
Reference
Pitfalls

I/O Params of a
Function

Recommended
Mechanisms

References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.2


Module Objectives

Module M07

• Understand References in C++

L
Partha Pratim
Das
• Compare and contrast References and Pointers

E
Objectives &
Outlines

T
Reference
Pitfalls

P
Call-by-Reference
Swap in C
Swap in C++

N
const Reference
Parameter

Return-by-
Reference
Pitfalls

I/O Params of a
Function

Recommended
Mechanisms

References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.3


Module Outline

Module M07
1 Reference Variable

L
Partha Pratim
Das
Pitfalls in Reference

E
Objectives &
Outlines 2 Call-by-Reference

T
Reference Simple C Program to swap
Pitfalls
Simple C/C++ Program to swap two numbers

P
Call-by-Reference
Swap in C
const Reference Parameter
Swap in C++

N
const Reference
Parameter
3 Return-by-Reference
Return-by-
Pitfalls of Return-by Reference
Reference
Pitfalls 4 I/O Parameters of a Function
I/O Params of a
Function
5 Recommended Call and Return Mechanisms
Recommended
Mechanisms

References vs.
6 Difference between Reference and Pointer
Pointers

Module Summary
7 Module Summary
Programming in Modern C++ Partha Pratim Das M07.4
Reference Variable

Module M07

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Reference
Pitfalls

P
Call-by-Reference
Swap in C
Swap in C++

N
const Reference
Parameter

Return-by-
Reference
Pitfalls

I/O Params of a
Function Reference Variable
Recommended
Mechanisms

References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.5


Reference

Module M07

• A reference is an alias / synonym for an existing variable

L
Partha Pratim
Das
int i = 15; // i is a variable

E
Objectives &
Outlines int &j = i; // j is a reference to i

T
Reference
Pitfalls
i ← variable

P
Call-by-Reference
Swap in C 15 ← memory content
Swap in C++
← address &i = &j

N
200
const Reference
Parameter
j ← alias or reference
Return-by-
Reference
Pitfalls

I/O Params of a
Function

Recommended
Mechanisms

References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.6


Program 07.01: Behavior of Reference
#include <iostream>
Module M07
using namespace std;

L
Partha Pratim
Das int main() {
int a = 10, &b = a; // b is reference of a

E
Objectives &
Outlines
// a and b have the same memory location

T
Reference cout << "a = " << a << ", b = " << b << ". " << "&a = " << &a << ", &b = " << &b << endl;
Pitfalls

P
Call-by-Reference ++a; // Changing a appears as change in b
Swap in C cout << "a = " << a << ", b = " << b << endl;
Swap in C++

N
const Reference ++b; // Changing b also changes a
Parameter
cout << "a = " << a << ", b = " << b << endl;
Return-by- }
Reference
Pitfalls

I/O Params of a a = 10, b = 10. &a = 002BF944, &b = 002BF944


Function a = 11, b = 11
Recommended a = 12, b = 12
Mechanisms

References vs.
Pointers • a and b have the same memory location and hence the same value
• Changing one changes the other and vice-versa
Module Summary

Programming in Modern C++ Partha Pratim Das M07.7


Pitfalls in Reference

Module M07 Wrong declaration Reason Correct declaration

L
Partha Pratim
Das int& i; no variable (address) to refer to – must be initialized int& i = j;
int& j = 5; no address to refer to as 5 is a constant const int& j = 5;

E
Objectives &
Outlines int& i = j + k; only temporary address (result of j + k) to refer to const int& i = j + k;

T
Reference
Pitfalls #include <iostream>

P
Call-by-Reference using namespace std;
Swap in C
Swap in C++
int main() {

N
const Reference
Parameter int i = 2;
Return-by- int& j = i;
Reference
const int& k = 5; // const tells compiler to allocate a memory with the value 5
Pitfalls
const int& l = j + k; // Similarly for j + k = 7 for l to refer to
I/O Params of a
Function

Recommended
cout << i << ", " << &i << endl; // Prints: 2, 0x61fef8
Mechanisms cout << j << ", " << &j << endl; // Prints: 2, 0x61fef8
References vs. cout << k << ", " << &k << endl; // Prints: 5, 0x61fefc
Pointers cout << l << ", " << &l << endl; // Prints: 7, 0x61ff00
Module Summary }
Programming in Modern C++ Partha Pratim Das M07.8
Call-by-Reference

Module M07

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Reference
Pitfalls

P
Call-by-Reference
Swap in C
Swap in C++

N
const Reference
Parameter

Return-by-
Reference
Pitfalls

I/O Params of a
Function Call-by-Reference
Recommended
Mechanisms

References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.9


C++ Program 07.02: Call-by-Reference

Module M07 #include <iostream>


using namespace std;

L
Partha Pratim
Das
void Function_under_param_test( // Function prototype
int&, // Reference parameter

E
Objectives &
Outlines int); // Value parameter

T
Reference
Pitfalls
int main() { int a = 20;
cout << "a = " << a << ", &a = " << &a << endl << endl;

P
Call-by-Reference
Function_under_param_test(a, a); // Function call
Swap in C
}
Swap in C++
void Function_under_param_test(int &b, int c) { // Function definition

N
const Reference
Parameter cout << "b = " << b << ", &b = " << &b << endl << endl;
Return-by-
cout << "c = " << c << ", &c = " << &c << endl << endl;
Reference }
Pitfalls ------- Output -------
a = 20, &a = 0023FA30
I/O Params of a
Function b = 20, &b = 0023FA30 // Address of b is same as a as b is a reference of a
c = 20, &c = 0023F95C // Address different from a as c is a copy of a
Recommended
Mechanisms • Param b is call-by-reference while param c is call-by-value
References vs. • Actual param a and formal param b get the same value in called function
Pointers • Actual param a and formal param c get the same value in called function
Module Summary
• Actual param a and formal param b get the same address in called function
• However, actual param a and formal param c have different addresses in called function
Programming in Modern C++ Partha Pratim Das M07.10
C Program 07.03: Swap in C

Module M07 Call-by-value – wrong Call-by-address – right

L
Partha Pratim
Das
#include <stdio.h> #include <stdio.h>

E
Objectives & void swap(int, int); // Call-by-value void swap(int *, int *); // Call-by-address
Outlines int main() { int a = 10, b = 15; int main() { int a=10, b=15;
printf("a= %d & b= %d to swap\n", a, b); printf("a= %d & b= %d to swap\n", a, b);

T
Reference
Pitfalls
swap(a, b); swap(&a, &b); // Unnatural call
printf("a= %d & b= %d on swap\n", a, b); printf("a= %d & b= %d on swap\n", a, b);

P
Call-by-Reference
} }
Swap in C
void swap(int c, int d) { int t; void swap(int *x, int *y) { int t;
Swap in C++

N
const Reference
t = c; c = d; d = t; t = *x; *x = *y; *y = t;
Parameter } }
Return-by-
Reference
Pitfalls • a= 10 & b= 15 to swap • a= 10 & b= 15 to swap
I/O Params of a
• a= 10 & b= 15 on swap // No swap • a= 15 & b= 10 on swap // Correct swap
Function

Recommended
Mechanisms • Passing values of a=10 & b=15 • Passing Address of a & b
• In callee; c = 10 & d = 15 • In callee x = Addr(a) & y = Addr(b)
References vs.
Pointers
• Swapping the values of c & d • Values at the addresses is swapped
• No change for the values of a & b in caller • Desired changes for the values of a & b in caller
Module Summary • Swapping the value of c & d instead of a & b • It is correct, but C++ has a better way out
Programming in Modern C++ Partha Pratim Das M07.11
Program 07.04: Swap in C & C++

Module M07
C Program: Call-by-value – wrong C++ Program: Call-by-reference – right

L
Partha Pratim
Das #include <stdio.h> #include <iostream>
using namespace std;

E
Objectives & void swap(int, int); // Call-by-value void swap(int&, int&); // Call-by-reference
Outlines
int main() { int a = 10, b = 15; int main() { int a = 10, b = 15;

T
Reference printf("a= %d & b= %d to swap\n",a,b); cout<<"a= "<<a<<" & b= "<<b<<"to swap"<<endl;
Pitfalls swap(a, b); swap(a, b); // Natural call
printf("a= %d & b= %d on swap\n",a,b); cout<<"a= "<<a<<" & b= "<<b<<"on swap"<<endl;

P
Call-by-Reference
Swap in C } }
Swap in C++ void swap(int c, int d) { int t ; void swap(int &x, int &y) { int t ;

N
const Reference t = c; c = d; d = t; t = x; x = y; y = t;
Parameter
} }
Return-by-
Reference
Pitfalls
• a= 10 & b= 15 to swap • a= 10 & b= 15 to swap
I/O Params of a • a= 10 & b= 15 on swap // No swap • a= 15 & b= 10 on swap // Correct swap
Function

Recommended
Mechanisms • Passing values of a=10 & b=15 • Passing values of a = 10 & b = 15
References vs. • In callee; c = 10 & d = 15 • In callee: x = 10 & y = 15
Pointers • Swapping the values of c & d • Swapping the values of x & y
Module Summary
• No change for the values of a & b in caller • Desired changes for the values of a & b in caller
• Here c & d do not share address with a & b • x & y having same address as a & b respectively
Programming in Modern C++ Partha Pratim Das M07.12
Program 07.05: Reference Parameter as const

Module M07
• A reference parameter may get changed in the called function
• Use const to stop reference parameter being changed

L
Partha Pratim
Das
const reference – bad const reference – good

E
Objectives &
Outlines #include <iostream> #include <iostream>

T
Reference using namespace std; using namespace std;
Pitfalls
int Ref_const(const int &x) { int Ref_const(const int &x) {

P
Call-by-Reference
Swap in C
++x; // Not allowed
Swap in C++
return (x); return (x + 1);

N
const Reference } }
Parameter int main() { int a = 10, b; int main() { int a = 10, b;
Return-by- b = Ref_const(a); b = Ref_const(a);
Reference cout << "a = " << a <<" and" cout << "a = " << a << " and"
Pitfalls << " b = " << b; << " b = " << b;
I/O Params of a } }
Function

Recommended
Mechanisms
• Error: Increment of read only Reference ’x’ a = 10 and b = 11
References vs.
Pointers
• Compilation Error: Value of x cannot be changed • No violation
Module Summary • Implies, a cannot be changed through x
Programming in Modern C++ Partha Pratim Das M07.13
Return-by-Reference

Module M07

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Reference
Pitfalls

P
Call-by-Reference
Swap in C
Swap in C++

N
const Reference
Parameter

Return-by-
Reference
Pitfalls

I/O Params of a
Function Return-by-Reference
Recommended
Mechanisms

References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.14


Program 07.06: Return-by-Reference

Module M07 • A function can return a value by reference (Return-by-Reference)


• C uses Return-by-value

L
Partha Pratim
Das Return-by-value Return-by-reference

E
Objectives & #include <iostream> #include <iostream>
Outlines using namespace std; using namespace std;

T
Reference int Function_Return_By_Val(int &x) { int& Function_Return_By_Ref(int &x) {
Pitfalls cout << "x = " << x << " &x = " << &x << endl; cout << "x = " << x << " &x = " << &x << endl;
return (x); return (x);

P
Call-by-Reference
Swap in C
} }
Swap in C++
int main() { int a = 10; int main() { int a = 10;

N
const Reference cout << "a = " << a << " &a = " << &a << endl; cout << "a = " << a << " &a = " << &a << endl;
Parameter const int& b = // const needed. Why? const int& b = // const optional
Return-by- Function_Return_By_Val(a); Function_Return_By_Ref(a);
Reference cout << "b = " << b << " &b = " << &b << endl; cout << "b = " << b << " &b = " << &b << endl;
Pitfalls } }
I/O Params of a
Function
a = 10 &a = 00DCFD18 a = 10 &a = 00A7F8FC
Recommended
Mechanisms
x = 10 &x = 00DCFD18 x = 10 &x = 00A7F8FC
b = 10 &b = 00DCFD00 // Reference to temporary b = 10 &b = 00A7F8FC // Reference to a
References vs.
Pointers

Module Summary • Returned variable is temporary • Returned variable is an alias of a


• Has a different address • Has the same address
Programming in Modern C++ Partha Pratim Das M07.15
Program 07.07: Return-by-Reference can get tricky

Module M07 Return-by-reference Return-by-reference – Risky!

L
Partha Pratim #include <iostream> #include <iostream>
Das using namespace std; using namespace std;
int& Return_ref(int &x) { int& Return_ref(int &x) {

E
Objectives &
Outlines
int t = x;
t++;

T
Reference return (x); return (t);
Pitfalls
} }

P
Call-by-Reference int main() { int a = 10, b = Return_ref(a); int main() { int a = 10, b = Return_ref(a);
Swap in C cout << "a = " << a << " and b = " cout << "a = " << a << " and b = "
Swap in C++ << b << endl; << b << endl;

N
const Reference
Parameter
Return_ref(a) = 3; // Changes variable a Return_ref(a) = 3; // Changes local t
Return-by- cout << "a = " << a; cout << "a = " << a;
Reference
Pitfalls
} }
I/O Params of a
Function a = 10 and b = 10 a = 10 and b = 11
Recommended a=3 a = 10
Mechanisms

References vs.
Pointers • Note how a value is assigned to function call • We expect a to be 3, but it has not changed
Module Summary • This can change a local variable • It returns reference to local. This is risky

Programming in Modern C++ Partha Pratim Das M07.16


I/O Parameters of a Function

Module M07

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Reference
Pitfalls

P
Call-by-Reference
Swap in C
Swap in C++

N
const Reference
Parameter

Return-by-
Reference
Pitfalls

I/O Params of a
Function I/O Parameters of a Function
Recommended
Mechanisms

References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.17


I/O of a Function

Module M07

• In C++ we can change values with a function as follows:

L
Partha Pratim
Das

E
Objectives &
Outlines
I/O of Function Purpose Mechanism
Value Parameter Input Call-by-value

T
Reference
Pitfalls Reference Parameter In-Out Call-by-reference

P
Call-by-Reference
Swap in C
const Reference Parameter Input Call-by-reference
Swap in C++ Return Value Output Return-by-value

N
const Reference
Parameter Return-by-reference
Return-by-
Reference
const Return-by-reference
Pitfalls

I/O Params of a
Function • In addition, we can use the Call-by-address (Call-by-value with pointer) and
Recommended Return-by-address (Return-by-value with pointer) as in C
Mechanisms

References vs. • But it is neither required nor advised


Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.18


Recommended Mechanisms

Module M07

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Reference
Pitfalls

P
Call-by-Reference
Swap in C
Swap in C++

N
const Reference
Parameter

Return-by-
Reference
Pitfalls

I/O Params of a
Function Recommended Mechanisms
Recommended
Mechanisms

References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.19


Recommended Mechanisms

Module M07

• Call

L
Partha Pratim
Das
◦ Pass parameters of built-in types by value

E
Objectives &
Outlines . Recall: Array parameters are passed by reference in C and C++

T
Reference
Pitfalls
◦ Pass parameters of user-defined types by reference
. Make a reference parameter const if it is not used for output

P
Call-by-Reference
Swap in C
Swap in C++ • Return

N
const Reference
Parameter ◦ Return built-in types by value
Return-by-
Reference
◦ Return user-defined types by reference
Pitfalls
. Return value is not copied back
I/O Params of a
Function . May be faster than returning a value
Recommended . Beware: Calling function can change returned object
Mechanisms
. Never return a local variables by reference
References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.20


Difference between Reference and Pointer

Module M07

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Reference
Pitfalls

P
Call-by-Reference
Swap in C
Swap in C++

N
const Reference
Parameter

Return-by-
Reference
Pitfalls

I/O Params of a
Function Difference between Reference and Pointer
Recommended
Mechanisms

References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.21


Difference between Reference and Pointer

Module M07
Pointers References

L
Partha Pratim
Das • Refers to an address (exposed) • Refers to an address (hidden)
• Pointers can point to NULL • References cannot be NULL

E
Objectives &
Outlines

T
Reference int *p = NULL; // p is not pointing int &j ; // wrong
Pitfalls
• Pointers can point to different variables at • For a reference, its referent is fixed

P
Call-by-Reference
Swap in C different times
Swap in C++
int a, b, *p; int a, c, &b = a; // Okay

N
const Reference
Parameter p = &a; // p points to a ...
Return-by-
Reference
... &b = c // Error
Pitfalls p = &b; // p points to b
I/O Params of a
Function • NULL checking is required • Does not require NULL checking
Recommended
Mechanisms
• Makes code faster
References vs.
• Allows users to operate on the address • Does not allow users to operate on the address
Pointers • diff pointers, increment, etc. • All operations are interpreted for the referent
Module Summary • Array of pointers can be defined • Array of references not allowed
Programming in Modern C++ Partha Pratim Das M07.22
Module Summary

Module M07

• Introduced reference in C++

L
Partha Pratim
Das
• Studied the difference between call-by-value and call-by-reference

E
Objectives &
Outlines • Studied the difference between return-by-value and return-by-reference

T
Reference
Pitfalls • Discussed the difference between References and Pointers

P
Call-by-Reference
Swap in C
Swap in C++

N
const Reference
Parameter

Return-by-
Reference
Pitfalls

I/O Params of a
Function

Recommended
Mechanisms

References vs.
Pointers

Module Summary

Programming in Modern C++ Partha Pratim Das M07.23


Module M08

L
Partha Pratim
Das
Programming in Modern C++

E
Objectives &
Outline
Module M08: Default Parameters & Function Overloading

T
Default
Parameters
Examples

P
Highlights
Restrictions
Partha Pratim Das

N
Function
Overloading
Examples
Restrictions
Department of Computer Science and Engineering
Rules
Indian Institute of Technology, Kharagpur
Overload
Resolution
ppd@cse.iitkgp.ac.in
Exact Match
Promotion &
Conversion All url’s in this module have been accessed in September, 2021 and found to be functional
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.1
Module Recap

Module M08

• Introduced reference in C++

L
Partha Pratim
Das
• Studied the difference between call-by-value and call-by-reference

E
Objectives &
Outline • Studied the difference between return-by-value and return-by-reference

T
Default
Parameters • Discussed the difference between References and Pointers
Examples

P
Highlights
Restrictions

N
Function
Overloading
Examples
Restrictions
Rules

Overload
Resolution
Exact Match
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.2
Module Objectives

Module M08

• Understand Default Parameters

L
Partha Pratim
Das
• Understand Function Overloading and Resolution

E
Objectives &
Outline

T
Default
Parameters
Examples

P
Highlights
Restrictions

N
Function
Overloading
Examples
Restrictions
Rules

Overload
Resolution
Exact Match
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.3
Module Outline

Module M08 1 Default Parameters


Examples

L
Partha Pratim
Das
Highlights

E
Objectives &
Outline Restrictions on default parameters

T
Default
Parameters 2 Function Overloading
Examples
Examples

P
Highlights
Restrictions Restrictions

N
Function
Overloading
Rules
Examples
Restrictions
3 Overload Resolution
Rules Exact Match
Overload
Resolution
Promotion & Conversion
Exact Match Examples
Promotion &
Conversion Ambiguity
Examples
Ambiguity 4 How to overload Default Parameter
Default
Parameters in 5 Module Summary
Overloading
Programming in Modern C++ Partha Pratim Das M08.4
Default Parameters

Module M08

L
Partha Pratim
Das

E
Objectives &
Outline

T
Default
Parameters
Examples

P
Highlights
Restrictions

N
Function
Overloading
Examples
Restrictions
Rules

Overload
Resolution
Exact Match
Default Parameters
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.5
Motivation: Example CreateWindow in MSVC++
Declaration of CreateWindow Calling CreateWindow
Module M08

L
Partha Pratim HWND WINAPI CreateWindow( hWnd = CreateWindow(
Das
_In_opt_ LPCTSTR lpClassName, ClsName,

E
Objectives & _In_opt_ LPCTSTR lpWindowName, WndName,
Outline
_In_ DWORD dwStyle, WS_OVERLAPPEDWINDOW,

T
Default _In_ int x, CW_USEDEFAULT,
Parameters
Examples
_In_ int y, CW_USEDEFAULT,

P
Highlights _In_ int nWidth, CW_USEDEFAULT,
Restrictions _In_ int nHeight, CW_USEDEFAULT,

N
Function _In_opt_ HWND hWndParent, NULL,
Overloading
Examples
_In_opt_ HMENU hMenu, NULL,
Restrictions _In_opt_ HINSTANCE hInstance, hInstance,
Rules _In_opt_ LPVOID lpParam NULL
Overload ); );
Resolution
Exact Match
Promotion & • There are 11 parameters in CreateWindow()
Conversion
Examples
• Of these 11, 8 parameters (4 are CWUSEDEFAULT, 3 are NULL, and 1 is hInstance) usually get same
Ambiguity values in most calls
Default • Instead of using these 8 fixed valued Parameters at call, we may assign the values in formal parameter
Parameters in
Overloading
• C++ allows us to do so through the mechanism called Default parameters
Programming in Modern C++ Partha Pratim Das M08.6
Program 08.01: Function with a default parameter

Module M08
#include <iostream>

L
Partha Pratim
Das using namespace std;

E
Objectives &
Outline int IdentityFunction(int a = 10) { // Default value for parameter a
return (a);

T
Default
Parameters }
Examples

P
Highlights
Restrictions
int main() {
int x = 5, y;

N
Function
Overloading
Examples y = IdentityFunction(x); // Usual function call. Actual parameter taken as x = 5
Restrictions
Rules
cout << "y = " << y << endl;
Overload
Resolution y = IdentityFunction(); // Uses default parameter. Actual parameter taken as 10
Exact Match cout << "y = " << y << endl;
Promotion &
Conversion
}
Examples ----------
Ambiguity y = 5
Default y = 10
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.7
Program 08.02: Function with 2 default parameters
#include<iostream>
Module M08
using namespace std;

L
Partha Pratim
Das
int Add(int a = 10, int b = 20) {

E
Objectives & return (a + b);
Outline
}

T
Default int main() { int x = 5, y = 6, z;
Parameters
Examples

P
Highlights z = Add(x, y); // Usual function call -- a = x = 5 & b = y = 6
Restrictions cout << "Sum = " << z << endl;

N
Function
Overloading
Examples
z = Add(x); // One parameter defaulted -- a = x = 5 & b = 20
Restrictions cout << "Sum = " << z << endl;
Rules

Overload z = Add(); // Both parameter defaulted -- a = 10 & b = 20


Resolution
cout << "Sum = " << z << endl;
Exact Match
Promotion &
}
Conversion
----------
Examples
Ambiguity
Sum = 11
Default
Sum = 25
Parameters in Sum = 30
Overloading
Programming in Modern C++ Partha Pratim Das M08.8
Default Parameter: Highlighted Points

Module M08

• C++ allows programmer to assign default values to the function parameters

L
Partha Pratim
Das
• Default values are specified while prototyping the function

E
Objectives &
Outline • Default parameters are required while calling functions with fewer arguments or without

T
Default
Parameters
any argument
Examples
• Better to use default value for less used parameters

P
Highlights
Restrictions
• Default arguments may be expressions also

N
Function
Overloading
Examples
Restrictions
Rules

Overload
Resolution
Exact Match
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.9
Restrictions on default parameters

Module M08
• All parameters to the right of a parameter with default argument must have default
arguments (function f violates)

L
Partha Pratim
Das
• Default arguments cannot be re-defined (second signature of function g violates)

E
Objectives &
Outline • All non-defaulted parameters needed in a call (first call of g() violates)
#include <iostream>

T
Default
Parameters
Examples void f(int, double = 0.0, char *);

P
Highlights // Error C2548: f: missing default parameter for parameter 3
Restrictions

N
Function void g(int, double = 0, char * = NULL); // OK
Overloading void g(int, double = 1, char * = NULL);
Examples // Error C2572: g: redefinition of default parameter : parameter 3
Restrictions // Error C2572: g: redefinition of default parameter : parameter 2
Rules

Overload int main() {


Resolution int i = 5; double d = 1.2; char c = ’b’;
Exact Match
Promotion &
Conversion g(); // Error C2660: g: function does not take 0 arguments
Examples g(i);
Ambiguity g(i, d);
Default
g(i, d, &c);
Parameters in }
Overloading
Programming in Modern C++ Partha Pratim Das M08.10
Restrictions on default parameters

Module M08 • Default parameters to be supplied only in a header file and not in the definition of a
function

L
Partha Pratim
Das
// Header file: myFunc.h

E
Objectives & void g(int, double, char = ’a’); // Defaults ch
Outline
void g(int i, double f = 0.0, char ch); // A new overload. Defaults f & ch

T
Default void g(int i = 0, double f, char ch); // A new overload. Defaults i, f & ch
Parameters
// void g(int i = 0, double f = 0.0, char ch = ’a’); // Alternate signature. Defaults all in one go
Examples

P
----------------------------------------------------
Highlights
// Source File
Restrictions
#include <iostream>

N
Function using namespace std;
Overloading
#include "myFunc.h" // Defaults taken from header
Examples
Restrictions
void g(int i, double d, char c) { cout << i << ’ ’ << d << ’ ’ << c << endl; } // No defaults here
Rules
----------------------------------------------------
// Application File
Overload
Resolution
#include <iostream>
Exact Match
#include "myFunc.h"
Promotion &
int main() { int i = 5; double d = 1.2; char c = ’b’;
Conversion g(); // Prints: 0 0 a
Examples g(i); // Prints: 5 0 a
Ambiguity
g(i, d); // Prints: 5 1.2 a
Default g(i, d, c); // Prints: 5 1.2 b
Parameters in }
Overloading
Programming in Modern C++ Partha Pratim Das M08.11
Function Overloading

Module M08

L
Partha Pratim
Das

E
Objectives &
Outline

T
Default
Parameters
Examples

P
Highlights
Restrictions

N
Function
Overloading
Examples
Restrictions
Rules

Overload
Resolution
Exact Match
Function Overloading
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.12
Function overloads: Matrix Multiplication in C

Module M08
• Similar functions with different data types and algorithms
typedef struct { int data[10][10]; } Mat;

L
Partha Pratim // 2D Matrix
Das typedef struct { int data[1][10]; } VecRow; // Row Vector
typedef struct { int data[10][1]; } VecCol; // Column Vector

E
Objectives &
Outline
void Multiply_M_M (Mat a, Mat b, Mat* c); // c = a * b

T
Default
Parameters
void Multiply_M_VC (Mat a, VecCol b, VecCol* c); // c = a * b
Examples
void Multiply_VR_M (VecRow a, Mat b, VecRow* c); // c = a * b

P
Highlights
void Multiply_VC_VR(VecCol a, VecRow b, Mat* c); // c = a * b
Restrictions void Multiply_VR_VC(VecRow a, VecCol b, int* c); // c = a * b

N
Function
Overloading int main() {
Examples Mat m1, m2, rm; VecRow rv, rrv; VecCol cv, rcv; int r;
Restrictions Multiply_M_M (m1, m2, &rm); // rm <-- m1 * m2
Rules Multiply_M_VC (m1, cv, &rcv); // rcv <-- m1 * cv
Overload
Multiply_VR_M (rv, m2, &rrv); // rrv <-- rv * m2
Resolution Multiply_VC_VR(cv, rv, &rm); // rm <-- cv * rv
Exact Match Multiply_VR_VC(rv, cv, &r); // r <-- rv * cv
Promotion & return 0;
Conversion
}
Examples
Ambiguity • 5 multiplication functions share similar functionality but different argument types
• C treats them by 5 different function names. Makes it difficult for the user to remember and use
Default
Parameters in • C++ has an elegant solution
Overloading
Programming in Modern C++ Partha Pratim Das M08.13
Function overloads: Matrix Multiplication in C++

Module M08
• Functions having the same name, similar functionality but different algorithms, and identified
by different interfaces data types

L
Partha Pratim
Das
typedef struct { int data[10][10]; } Mat; // 2D Matrix
typedef struct { int data[1][10]; } VecRow; // Row Vector

E
Objectives &
Outline typedef struct { int data[10][1]; } VecCol; // Column Vector

T
Default
Parameters void Multiply(const Mat& a, const Mat& b, Mat& c); // c = a * b
Examples void Multiply(const Mat& a, const VecCol& b, VecCol& c); // c = a * b

P
Highlights void Multiply(const VecRow& a, const Mat& b, VecRow& c); // c = a * b
Restrictions void Multiply(const VecCol& a, const VecRow& b, Mat& c); // c = a * b

N
Function void Multiply(const VecRow& a, const VecCol& b, int& c); // c = a * b
Overloading
Examples int main() {
Restrictions Mat m1, m2, rm; VecRow rv, rrv; VecCol cv, rcv; int r;
Rules
Multiply(m1, m2, rm); // rm <-- m1 * m2
Overload Multiply(m1, cv, rcv); // rcv <-- m1 * cv
Resolution Multiply(rv, m2, rrv); // rrv <-- rv * m2
Exact Match
Multiply(cv, rv, rm); // rm <-- cv * rv
Promotion &
Conversion Multiply(rv, cv, r); // r <-- rv * cv
Examples return 0;
Ambiguity }
Default • These 5 functions having different argument types are represented as one function name (Multiply) in C++
Parameters in • This is called Function Overloading or Static Polymorphism
Overloading
Programming in Modern C++ Partha Pratim Das M08.14
Program 08.03/04: Function Overloading

Module M08
• Define multiple functions having the same name
• Binding happens at compile time

L
Partha Pratim
Das
Same # of Parameters Different # of Parameters

E
Objectives &
Outline #include <iostream> #include <iostream>

T
Default using namespace std; using namespace std;
Parameters int Add(int a, int b) { return (a + b); } int Area(int a, int b) return (a * b);
Examples double Add(double c, double d) { return (c + d); } int Area(int c) { return (c * c); }

P
Highlights
int main() { int main() {
Restrictions
int x = 5, y = 6, z; int x = 10, y = 12, z = 5, t;

N
Function z = Add(x, y); // int Add(int, int) t = Area(x, y); // int Area(int, int)
Overloading cout << "int sum = " << z; cout << "Area of Rectangle = " << t;
Examples
Restrictions
double s = 3.5, t = 4.25, u; int z = 5, u;
Rules
u = Add(s, t); // double Add(double, double) u = Area(z); // int Area(int)
Overload cout << "double sum = " << u << endl; cout << " Area of Square = " << u << endl;
Resolution
} }
Exact Match
Promotion &
Conversion int sum = 11 double sum = 7.75 Area of Rectangle = 12 Area of Square = 25
Examples
Ambiguity • Same Add function to add two ints or two doubles • Same Area function for rectangles and for squares
Default • Same # of parameters but different types • Different number of parameters
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.15
Program 08.05: Restrictions in Function Overloading

Module M08 • Two functions having the same signature but different return types cannot be overloaded
#include <iostream>

L
Partha Pratim
Das using namespace std;

E
Objectives &
Outline
int Area(int a, int b) { return (a * b); }
double Area(int a, int b) { return (a * b); }

T
Default // Error C2556: double Area(int,int): overloaded function differs only by return type
Parameters
// from int Area(int,int)
Examples

P
Highlights
// Error C2371: Area: redefinition; different basic types
Restrictions
int main() {

N
Function
Overloading
int x = 10, y = 12, z = 5, t;
Examples
double f;
Restrictions
Rules t = Area(x, y);
// Error C2568: =: unable to resolve function overload
Overload
Resolution // Error C3861: Area: identifier not found
Exact Match
Promotion & cout << "Multiplication = " << t << endl;
Conversion
Examples
f = Area(y, z); // Errors C2568 and C3861 as above
Ambiguity
cout << "Multiplication = " << f << endl;
Default }
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.16
Function Overloading: Summary of Rules

Module M08

• The same function name may be used in several definitions

L
Partha Pratim
Das
• Functions with the same name must have different number of formal parameters and/or

E
Objectives &
Outline different types of formal parameters

T
Default
Parameters
• Function selection is based on the number and the types of the actual parameters at
Examples the places of invocation

P
Highlights
Restrictions
• Function selection (Overload Resolution) is performed by the compiler

N
Function
Overloading • Two functions having the same signature but different return types will result in a
Examples
Restrictions
compilation error due to attempt to re-declare
Rules
• Overloading allows Static Polymorphism
Overload
Resolution
Exact Match
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.17
Overload Resolution

Module M08

L
Partha Pratim
Das

E
Objectives &
Outline

T
Default
Parameters
Examples

P
Highlights
Restrictions

N
Function
Overloading
Examples
Restrictions
Rules

Overload
Resolution
Exact Match
Overload Resolution
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.18
Overload Resolution

Module M08

• To resolve overloaded functions with one parameter

L
Partha Pratim
Das
◦ Identify the set of Candidate Functions

E
Objectives &
Outline ◦ From the set of candidate functions identify the set of Viable Functions
◦ Select the Best viable function through (Order is important)

T
Default
Parameters
Examples . Exact Match

P
Highlights
Restrictions
. Promotion
. Standard type conversion

N
Function
Overloading
Examples
. User defined type conversion
Restrictions
Rules

Overload
Resolution
Exact Match
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.19
Overload Resolution: Exact Match

Module M08

• lvalue-to-rvalue conversion: Read the value from an object

L
Partha Pratim
Das
◦ Most common

E
Objectives &
Outline • Array-to-pointer conversion

T
Default
Parameters
Definitions: int ar[10];
Examples void f(int *a);

P
Highlights
Restrictions
Call: f(ar)

N
Function
Overloading
Definitions: typedef int (*fp) (int);
Examples void f(int, fp);
Restrictions • Function-to-pointer conversion
Rules int g(int);
Overload Call: f(5, g)
Resolution
Exact Match • Qualification conversion
Promotion &
Conversion
Examples
◦ Converting pointer (only) to const pointer
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.20
Overload Resolution: Promotion & Conversion

Module M08

• Promotion

L
Partha Pratim
Das
◦ Objects of an integral type can be converted to another wider integral type, that is,

E
Objectives &
Outline a type that can represent a larger set of values. This widening type of conversion is
called integral promotion

T
Default
Parameters
Examples
◦ C++ promotions are value-preserving, as the value after the promotion is

P
Highlights
Restrictions
guaranteed to be the same as the value before the promotion
◦ Examples

N
Function
Overloading
Examples
. char to int; float to double
Restrictions . enum to int / short / unsigned int / ...
Rules

Overload
. bool to int
Resolution
Exact Match
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.21
Overload Resolution: Promotion & Conversion

Module M08 • Standard Conversions


◦ Integral conversions between integral types – char, short, int, and long with or without

L
Partha Pratim
Das
qualifiers signed or unsigned

E
Objectives &
Outline ◦ Floating point Conversions from less precise floating type to a more precise floating type
like float to double or double to long double. Conversion can happen to a less precise

T
Default
Parameters
type, if it is in a range representable by that type
Examples

P
Highlights ◦ Conversions between integral and floating point types: Certain expressions can cause
Restrictions
objects of floating type to be converted to integral types, or vice versa. May be dangerous!

N
Function
Overloading . When an object of integral type is converted to a floating type, and the original value is
Examples
not representable exactly, the result is either the next higher or the next lower
Restrictions
Rules representable value
Overload . When an object of floating type is converted to an integral type, the fractional part is
Resolution
Exact Match
truncated, or rounded toward zero. A number like 1.3 is converted to 1, and -1.3 is
Promotion & converted to -1
Conversion
Examples ◦ Pointer Conversions: Pointers can be converted during assignment, initialization,
Ambiguity
comparison, and other expressions
Default
Parameters in ◦ Bool Conversion: int to bool or vice versa based on the context
Overloading
Programming in Modern C++ Partha Pratim Das M08.22
Example: Overload Resolution with one parameter

Module M08
• In the context of a list of function prototypes:

L
Partha Pratim
Das int g(double); // F1
void f(); // F2

E
Objectives &
Outline
void f(int); // F3
double h(void); // F4

T
Default int g(char, int); // F5
Parameters
Examples
void f(double, double = 3.4); // F6

P
Highlights
void h(int, double); // F7
Restrictions void f(char, char *); // F8
The call site to resolve is:

N
Function
Overloading
Examples
f(5.6);
Restrictions
Rules
• Resolution:
Overload
◦ Candidate functions (by name): F2, F3, F6, F8
Resolution ◦ Viable functions (by # of parameters): F3, F6
Exact Match ◦ Best viable function (by type double – Exact Match): F6
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.23
Example: Ambiguity in Overload Resolution

Module M08
• Consider the overloaded function signatures:

L
Partha Pratim
Das int fun(float a) {...} // Function 1
int fun(float a, int b) {...} // Function 2

E
Objectives &
Outline int fun(float x, int y = 5) {...} // Function 3

T
Default
Parameters int main() {
Examples
float p = 4.5, t = 10.5;

P
Highlights
Restrictions
int s = 30;

N
Function
Overloading fun(p, s); // CALL - 1
Examples fun(t); // CALL - 2
Restrictions
Rules
return 0;
}
Overload
Resolution
• CALL - 1: Matches Function 2 & Function 3
Exact Match
Promotion & • CALL - 2: Matches Function 1 & Function 3
Conversion
Examples • Results in ambiguity for both calls
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.24
Default Parameters in Overloading

Module M08

L
Partha Pratim
Das

E
Objectives &
Outline

T
Default
Parameters
Examples

P
Highlights
Restrictions

N
Function
Overloading
Examples
Restrictions
Rules

Overload
Resolution
Exact Match
Default Parameters in Overloading
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.25
Program 08.06/07: Default Parameter & Function Overload

Module M08
• Compilers deal with default parameters as a special case of function overloading
• These need to be mixed carefully

L
Partha Pratim
Das

E
Objectives & Default Parameters Function Overload
Outline

T
Default #include <iostream> #include <iostream>
Parameters using namespace std; using namespace std;
Examples int f(int a = 1, int b = 2); int f();

P
Highlights
int f(int);
Restrictions
int f(int, int);

N
Function
Overloading
int main() { int main() {
Examples
int x = 5, y = 6; int x = 5, y = 6;
Restrictions
Rules
f(); // a = 1, b = 2 f(); // int f();
Overload f(x); // a = x = 5, b = 2 f(x); // int f(int);
Resolution
f(x, y); // a = x = 5, b = y = 6 f(x, y); // int f(int, int);
Exact Match
Promotion &
} }
Conversion
Examples
Ambiguity • Function f has 2 parameters defaulted • Function f is overloaded with up to 2 parameters
Default • f can have 3 possible forms of call • f can have 3 possible forms of call
Parameters in • No overload here use default parameters. Can it?
Overloading
Programming in Modern C++ Partha Pratim Das M08.26
Program 08.08: Default Parameter & Function Overload

Module M08 • Function overloading can use default parameter


• However, with default parameters, the overloaded functions should still be resolvable

L
Partha Pratim
Das
#include <iostream>

E
Objectives & using namespace std;
Outline // Overloaded Area functions
int Area(int a, int b = 10) { return (a * b); }

T
Default
Parameters double Area(double c, double d) { return (c * d); }
Examples int main() { int x = 10, y = 12, t; double z = 20.5, u = 5.0, f;

P
Highlights t = Area(x); // Binds int Area(int, int = 10)
Restrictions cout << "Area = " << t << endl; // Area = 100

N
Function
Overloading t = Area(x, y); // Binds int Area(int, int = 10)
Examples cout << "Area = " << t << endl; // Area = 120
Restrictions
Rules f = Area(z, u); // Binds double Area(double, double)
Overload cout << "Area = " << f << endl; // Area = 102.5
Resolution
Exact Match f = Area(z); // Binds int Area(int, int = 10)
Promotion &
Conversion
cout << "Area = " << f << endl; // Area = 200
Examples
Ambiguity // Un-resolvable between int Area(int a, int b = 10) and double Area(double c, double d)
f = Area(z, y); // Error: call of overloaded Area(double&, int&) is ambiguous
Default
Parameters in }
Overloading
Programming in Modern C++ Partha Pratim Das M08.27
Program 08.09: Default Parameter & Function Overload

Module M08
• Function overloading with default parameters may fail

L
Partha Pratim
Das
#include <iostream>
using namespace std;

E
Objectives &
Outline int f();
int f(int = 0);

T
Default
Parameters int f(int, int);
Examples

P
Highlights int main() {
Restrictions int x = 5, y = 6;

N
Function
Overloading f(); // Error C2668: f: ambiguous call to overloaded function
Examples // More than one instance of overloaded function f
Restrictions // matches the argument list:
Rules // function f()
Overload // function f(int = 0)
Resolution
Exact Match f(x); // int f(int);
Promotion & f(x, y); // int f(int, int);
Conversion
Examples
Ambiguity
return 0;
}
Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.28
Module Summary

Module M08

• Introduced the notion of Default parameters and discussed several examples

L
Partha Pratim
Das
• Identified the necessity of function overloading

E
Objectives &
Outline • Introduced static Polymorphism and discussed examples and restrictions

T
Default
Parameters • Discussed an outline for Overload resolution
Examples

P
Highlights • Discussed the mix of default Parameters and function overloading
Restrictions

N
Function
Overloading
Examples
Restrictions
Rules

Overload
Resolution
Exact Match
Promotion &
Conversion
Examples
Ambiguity

Default
Parameters in
Overloading
Programming in Modern C++ Partha Pratim Das M08.29
Module M09

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
ppd@cse.iitkgp.ac.in
Enum

Rules
All url’s in this module have been accessed in September, 2021 and found to be functional
Restrictions

Module Summary

Programming in Modern C++ Partha Pratim Das M09.1


Module Recap

Module M09

• Introduced the notion of Default parameters and discussed several examples

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

Programming in Modern C++ Partha Pratim Das M09.2


Module Objectives

Module M09

• Understand the Operator Overloading

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

Programming in Modern C++ Partha Pratim Das M09.3


Module Outline

Module M09

1 Operators and functions

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

Programming in Modern C++ Partha Pratim Das M09.5


Operator & Function

Module M09

• What is the difference between an operator & a function?

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++

Operator // Computed by ’*’ operator


Overloading unsigned int c = a * b; // c is 6
Advantages and
Disadvantages
// Computed by Multiply function
Examples unsigned int d = Multiply(a, b); // d is 6
String
Enum
return 0;
Rules }
Restrictions
• Same computation by an operator and a function
Module Summary

Programming in Modern C++ Partha Pratim Das M09.6


Difference between Operator & Functions

Module M09 Operator Function

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

Examples • Operates on one or more operands, • Operates on zero or more arguments


String
Enum
typically up to 3 (Unary, Binary or Ternary)
Rules
• Produces one result • Produces up to one result
Restrictions
• Order of operations is decided by • Order of application is decided by depth of
Module Summary
precedence and associativity nesting
• Operators are pre-defined • Functions can be defined as needed
Programming in Modern C++ Partha Pratim Das M09.7
Operator Functions in C++

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

Programming in Modern C++ Partha Pratim Das M09.8


Operator Functions in C++

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

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


Module Summary
• C++ allows users to define an operator function and overload it
Programming in Modern C++ Partha Pratim Das M09.9
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
Operator Overloading
Rules

Restrictions

Module Summary

Programming in Modern C++ Partha Pratim Das M09.10


Operator Overloading

Module M09

• Operator Overloading (also called ad hoc polymorphism), is a specific case of

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

Programming in Modern C++ Partha Pratim Das M09.11


Operator Overloading: Advantages and Disadvantages

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

Programming in Modern C++ Partha Pratim Das M09.14


Program 09.01: String Concatenation

Module M09 Concatenation by string functions Concatenation operator

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+

Module M09 w/o Overloading + Overloading 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

Restrictions • Implicitly converts enum E values to int


Module Summary
• Adds by operator+ of int • operator + is overloaded for enum E
• Result is outside enum E range • Result is a valid enum E value

Programming in Modern C++ Partha Pratim Das M09.16


Operator Overloading 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

Programming in Modern C++ Partha Pratim Das M09.17


Operator Overloading: Rules

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

Programming in Modern C++ Partha Pratim Das M09.19


Overloading: Restrictions

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

• Introduced operator overloading with its advantages and disadvantages

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

Programming in Modern C++ Partha Pratim Das M09.21


Module M10

L
Partha Pratim
Das
Programming in Modern C++

E
Objectives &
Outline
Module M10: Dynamic Memory Management

T
Memory
Management in C
malloc & free

P
Memory
Management in
Partha Pratim Das

N
C++
new & delete
Array
Placement new Department of Computer Science and Engineering
Restrictions Indian Institute of Technology, Kharagpur
Overloading new
& delete ppd@cse.iitkgp.ac.in
Module Summary

All url’s in this module have been accessed in September, 2021 and found to be functional

Programming in Modern C++ Partha Pratim Das M10.1


Module Recap

Module M10

• Introduced operator overloading with its advantages and disadvantages

L
Partha Pratim
Das
• Explained the rules of operator overloading

E
Objectives &
Outline

T
Memory
Management in C
malloc & free

P
Memory
Management in

N
C++
new & delete
Array
Placement new
Restrictions

Overloading new
& delete

Module Summary

Programming in Modern C++ Partha Pratim Das M10.2


Module Objectives

Module M10

• Understand the dynamic memory management in C++

L
Partha Pratim
Das

E
Objectives &
Outline

T
Memory
Management in C
malloc & free

P
Memory
Management in

N
C++
new & delete
Array
Placement new
Restrictions

Overloading new
& delete

Module Summary

Programming in Modern C++ Partha Pratim Das M10.3


Module Outline

Module M10

L
Partha Pratim
Das 1 Dynamic Memory Management in C
malloc & free

E
Objectives &
Outline

T
Memory
Management in C
malloc & free
2 Dynamic Memory Management in C++

P
Memory
new and delete operator
Management in Dynamic memory allocation for Array

N
C++
new & delete Placement new
Array
Placement new Restrictions
Restrictions

Overloading new
& delete 3 Operator Overloading for Allocation and De-allocation
Module Summary

4 Module Summary

Programming in Modern C++ Partha Pratim Das M10.4


Dynamic Memory Management in C

Module M10

L
Partha Pratim
Das

E
Objectives &
Outline

T
Memory
Management in C
malloc & free

P
Memory
Management in

N
C++
new & delete
Array
Placement new
Restrictions

Overloading new
& delete

Module Summary
Dynamic Memory Management in C

Programming in Modern C++ Partha Pratim Das M10.5


Program 10.01/02: malloc() & free(): C & C++

Module M10
C Program C++ Program

L
Partha Pratim
Das #include <stdio.h> #include <iostream>
#include <stdlib.h> #include <cstdlib>

E
Objectives & using namespace std;
Outline

T
Memory int main() { int main() {
Management in C int *p = (int *)malloc(sizeof(int)); int *p = (int *)malloc(sizeof(int));
malloc & free *p = 5; *p = 5;

P
Memory
Management in printf("%d", *p); // Prints: 5 cout << *p; // Prints: 5

N
C++
new & delete
Array
free(p); free(p);
Placement new
} }
Restrictions

Overloading new
• Dynamic memory management functions in stdlib.h header for C (cstdlib header for C++)
& delete • malloc() allocates the memory on heap or free store
Module Summary
• sizeof(int) needs to be provided
• Pointer to allocated memory returned as void* – needs cast to int*
• Allocated memory is released by free() from heap or free store
• calloc() and realloc() also available in both languages

Programming in Modern C++ Partha Pratim Das M10.6


Dynamic Memory Management in C++

Module M10

L
Partha Pratim
Das

E
Objectives &
Outline

T
Memory
Management in C
malloc & free

P
Memory
Management in

N
C++
new & delete
Array
Placement new
Restrictions

Overloading new
& delete

Module Summary
Dynamic Memory Management in C++

Programming in Modern C++ Partha Pratim Das M10.7


Program 10.02/03: operator new & delete:
Dynamic memory management in C++
Module M10
• C++ introduces operators new and delete to dynamically allocate and de-allocate memory:

L
Partha Pratim
Das
Functions malloc() & free() operator new & operator delete

#include <iostream> #include <iostream>

E
Objectives &
Outline #include <cstdlib>
using namespace std; using namespace std;

T
Memory
Management in C
malloc & free int main() { int main() {

P
int *p = (int *)malloc(sizeof(int)); int *p = new int(5);
Memory
Management in *p = 5;
cout << *p; // Prints: 5 cout << *p; // Prints: 5

N
C++
new & delete
Array free(p); delete p;
Placement new } }
Restrictions

Overloading new
& delete • Function malloc() for allocation on heap • operator new for allocation on heap
Module Summary
• sizeof(int) needs to be provided • No size specification needed, type suffices
• Allocated memory returned as void* • Allocated memory returned as int*
• Casting to int* needed • No casting needed
• Cannot be initialized • Can be initialized
• Function free() for de-allocation from heap • operator delete for de-allocation from heap
• Library feature – header cstdlib needed • Core language feature – no header needed

Programming in Modern C++ Partha Pratim Das M10.8


Program 10.02/04: Functions:
operator new() & operator delete()
Module M10
• C++ also allows operator new() and operator delete() functions to dynamically allocate

L
Partha Pratim
Das and de-allocate memory:
Functions malloc() & free() Functions operator new() & operator delete()

E
Objectives &
Outline
#include <iostream> #include <iostream>

T
Memory #include <cstdlib> #include <cstdlib>
Management in C
using namespace std; using namespace std;
malloc & free

P
Memory int main() { int main() {
Management in
int *p = (int *)malloc(sizeof(int)); int *p = (int *)operator new(sizeof(int));

N
C++
new & delete *p = 5; *p = 5;
Array
Placement new cout << *p; // Prints: 5 cout << *p; // Prints: 5
Restrictions

Overloading new free(p); operator delete(p);


& delete } }
Module Summary

• Function malloc() for allocation on heap • Function operator new() for allocation on heap
• Function free() for de-allocation from heap • Function operator delete() for de-allocation from heap

There is a major difference between operator new and function operator new(). We explore this angle later

Programming in Modern C++ Partha Pratim Das M10.9


Program 10.05/06: new[] & delete[]:
Dynamically managed Arrays in C++
Module M10 Functions malloc() & free() operator new[] & operator delete[]

L
Partha Pratim #include <iostream> #include <iostream>
Das #include <cstdlib> using namespace std;
using namespace std;

E
Objectives &
Outline
int main() { int main() {

T
Memory int *a = (int *)malloc(sizeof(int)* 3); int *a = new int[3];
Management in C
malloc & free
a[0] = 10; a[1] = 20; a[2] = 30; a[0] = 10; a[1] = 20; a[2] = 30;

P
Memory for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
Management in
cout << "a[" << i << "] = " cout << "a[" << i << "] = "

N
C++
new & delete << a[i] << " "; << a[i] << " ";
Array
Placement new free(a); delete [] a;
Restrictions } }
Overloading new ----- -----
& delete a[0] = 10 a[1] = 20 a[2] = 30 a[0] = 10 a[1] = 20 a[2] = 30
Module Summary

• Allocation by malloc() on heap • Allocation by operator new[] (different from operator


new) on heap
• # of elements implicit in size passed to malloc() • # of elements explicitly passed to operator new[]
• Release by free() from heap • Release by operator delete[] (different from operator
delete) from heap
Programming in Modern C++ Partha Pratim Das M10.10
Program 10.07: Operator new():
Placement new in C++
#include <iostream>
Module M10
using namespace std;
int main() { unsigned char buf[sizeof(int)* 2]; // Byte buffer on stack

L
Partha Pratim
Das // placement new in buffer buf
int *pInt = new (buf) int (3);

E
Objectives &
Outline
int *qInt = new (buf+sizeof(int)) int (5);

T
Memory int *pBuf = (int *)(buf + 0); // *pInt in buf[0] to buf[sizeof(int)-1]
Management in C
int *qBuf = (int *)(buf + sizeof(int)); // *qInt in buf[sizeof(int)] to buf[2*sizeof(int)-1]
malloc & free

P
cout << "Buf Addr Int Addr" << pBuf << " " << pInt << endl << qBuf << " " << qInt << endl;
Memory cout << "1st Int 2nd Int" << endl << *pBuf << " " << *qBuf << endl;
Management in

N
C++
new & delete int *rInt = new int(7); // heap allocation
Array cout << "Heap Addr 3rd Int" << endl << rInt << " " << *rInt << endl;
Placement new delete rInt; // delete integer from heap
Restrictions // No delete for placement new
Overloading new
}
& delete -----
• Placement operator new takes a buffer address to place objects
Buf Addr Int Addr
Module Summary • These are not dynamically allocated on heap – may be allocated on stack or heap or static,
001BFC50 001BFC50
wherever the buffer is located
001BFC54 001BFC54
• Allocations by Placement operator new must not be deleted
1st Int 2nd Int
3 5
Heap Addr 3rd Int
003799B8 7
Programming in Modern C++ Partha Pratim Das M10.11
Mixing Allocators and De-allocators of C and C++

Module M10
• Allocation and De-allocation must correctly match.

L
Partha Pratim
Das ◦ Do not free the space created by new using free()
◦ And do not use delete if memory is allocated through malloc()

E
Objectives &
Outline
These may results in memory corruption

T
Memory
Management in C
malloc & free Allocator De-allocator

P
Memory malloc() free()
Management in
operator new operator delete

N
C++
new & delete
Array
operator new[] operator delete[]
Placement new operator new() No delete
Restrictions

Overloading new
& delete • Passing NULL pointer to delete operator is secure
Module Summary • Prefer to use only new and delete in a C++ program
• The new operator allocates exact amount of memory from Heap or Free Store
• new returns the given pointer type – no need to typecast
• new, new[ ] and delete, delete[] have separate semantics
Programming in Modern C++ Partha Pratim Das M10.12
Operator Overloading for Allocation and De-allocation

Module M10

L
Partha Pratim
Das

E
Objectives &
Outline

T
Memory
Management in C
malloc & free

P
Memory
Management in

N
C++
new & delete
Array
Placement new
Restrictions

Overloading new
& delete

Module Summary
Operator Overloading for Allocation and De-allocation

Programming in Modern C++ Partha Pratim Das M10.13


Program 10.08: Overloading
operator new and operator delete
Module M10 #include <iostream>
#include <stdlib.h>

L
Partha Pratim using namespace std;
Das

void* operator new(size_t n) { // Definition of Operator new

E
Objectives &
Outline cout << "Overloaded new" << endl;
void *ptr = malloc(n); // Memory allocated to ptr. Can be done by function operator new()

T
Memory
Management in C return ptr;
malloc & free }

P
void operator delete(void *p) { // Definition of operator delete
Memory
Management in cout << "Overloaded delete" << endl;
free(p); // Allocated memory released. Can be done by function operator delete()

N
C++
new & delete }
Array int main() { int *p = new int; // Calling overloaded operator new
Placement new *p = 30; // Assign value to the location
Restrictions  << *p << endl;
cout << "The value is :"
Overloading new delete p; // Calling overloaded operator delete
& delete } • operator new overloaded
Module Summary ----- • The first parameter of overloaded operator new must be size t
Overloaded new • The return type of overloaded operator new must be void*
The value is : 30 • The first parameter of overloaded operator delete must be void*
Overloaded delete • The return type of overloaded operator delete must be void
• More parameters may be used for overloading
• operator delete should not be overloaded (usually) with extra parameters
Programming in Modern C++ Partha Pratim Das M10.14
Program 10.09: Overloading
operator new[] and operator delete[]
Module M10 #include <iostream>
#include <cstdlib>

L
Partha Pratim using namespace std;
Das

void* operator new [] (size_t os, char setv) { // Fill the allocated array with setv

E
Objectives &
Outline void *t = operator new(os);
memset(t, setv, os);

T
Memory
Management in C
return t;
malloc & free }

P
void operator delete[] (void *ss) {
Memory
Management in
operator delete(ss);
}

N
C++
new & delete int main() {
Array char *t = new(’#’)char[10]; // Allocate array of 10 elements and fill with ’#’
Placement new
Restrictions cout << "p = " << (unsigned int) (t) << endl;
Overloading new for (int k = 0; k < 10; ++k)
& delete cout << t[k];
Module Summary
delete [] t;
} • operator new[] overloaded with initialization
----- • The first parameter of overloaded operator new[] must be size t
p = 19421992 • The return type of overloaded operator new[] must be void*
########## • Multiple parameters may be used for overloading
• operator delete [] should not be overloaded (usually) with extra parameters
Programming in Modern C++ Partha Pratim Das M10.15
Module Summary

Module M10

• Introduced new and delete for dynamic memory management in C++

L
Partha Pratim
Das
• Understood the difference between new, new[] and delete, delete[]

E
Objectives &
Outline • Compared memory management in C with C++

T
Memory
Management in C • Explored the overloading of new, new[] and delete, delete[] operators
malloc & free

P
Memory
Management in

N
C++
new & delete
Array
Placement new
Restrictions

Overloading new
& delete

Module Summary

Programming in Modern C++ Partha Pratim Das M10.16


Tutorial T02

L
Partha Pratim
Das
Programming in Modern C++

E
Tutorial Recap

Objectives & Tutorial T02: How to build a C/C++ program?: Part 2: Build Pipeline

T
Outline

Build Pipeline

P
Compilers
gcc and g++
Build with GCC Partha Pratim Das

N
C/C++ Dialects
C Dialects
C++ Dialects Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur
Standard Library
C Std. Lib.
C++ Std. Lib.
ppd@cse.iitkgp.ac.in
std
Header Conventions
All url’s in this module have been accessed in September, 2021 and found to be functional
Tutorial Summary

Programming in Modern C++ Partha Pratim Das T02.1


Tutorial Recap

Tutorial T02

• Understood the differences and relationships between source and header files

L
Partha Pratim
Das
• Understood how CPP can be harnessed to manage code during build

E
Tutorial Recap

Objectives &

T
Outline

Build Pipeline

P
Compilers
gcc and g++
Build with GCC

N
C/C++ Dialects
C Dialects
C++ Dialects

Standard Library
C Std. Lib.
C++ Std. Lib.
std
Header Conventions

Tutorial Summary

Programming in Modern C++ Partha Pratim Das T02.2


Tutorial Objective

Tutorial T02

• What is the build pipelines? Especially with reference to GCC

L
Partha Pratim
Das
• How to work with C/C++ dialects during build?

E
Tutorial Recap

Objectives &
• Understanding C/C++ Standard Libraries

T
Outline

Build Pipeline

P
Compilers
gcc and g++
Build with GCC

N
C/C++ Dialects
C Dialects
C++ Dialects

Standard Library
C Std. Lib.
C++ Std. Lib.
std
Header Conventions

Tutorial Summary

Programming in Modern C++ Partha Pratim Das T02.3


Tutorial Outline

Tutorial T02
1 Tutorial Recap

L
Partha Pratim
Das
2 Build Pipeline

E
Tutorial Recap Compilers, IDE, and Debuggers
Objectives & gcc and g++

T
Outline

Build Pipeline
Build with GCC

P
Compilers
gcc and g++ 3 C/C++ Dialects
Build with GCC
C Dialects

N
C/C++ Dialects
C Dialects
C++ Dialects
C++ Dialects

Standard Library
4 Standard Library
C Std. Lib. C Standard Library
C++ Std. Lib.
std C++ Standard Library
Header Conventions std
Tutorial Summary Header Conventions

5 Tutorial Summary
Programming in Modern C++ Partha Pratim Das T02.4
Build Pipeline

Tutorial T02

L
Partha Pratim
Das

E
Tutorial Recap

Objectives &

T
Outline

Build Pipeline

P
Compilers
gcc and g++
Build with GCC

N
C/C++ Dialects
C Dialects
C++ Dialects

Standard Library
C Std. Lib.
C++ Std. Lib.
std
Build Pipeline
Header Conventions

Tutorial Summary

Programming in Modern C++ Partha Pratim Das T02.5


Build Pipeline

Tutorial T02

L
Partha Pratim
Das

E
Tutorial Recap

Objectives &

T
Outline

Build Pipeline

P
Compilers
gcc and g++
Build with GCC

N
C/C++ Dialects
C Dialects
C++ Dialects

Standard Library
C Std. Lib.
C++ Std. Lib.
std
Header Conventions

Tutorial Summary

Source: GNU Compiler Collection, Wikiwand Accessed 13-Sep-21

Programming in Modern C++ Partha Pratim Das T02.6


Build Pipeline

Tutorial T02
• The C preprocessor (CPP) has the ability for the inclusion of header files, macro expansions,
conditional compilation, and line control. It works on .c, .cpp, and .h files and produces .i

L
Partha Pratim
Das
files

E
Tutorial Recap

Objectives &
• The Compiler translates the pre-processed C/C++ code into assembly language, which is a

T
Outline machine level code in text that contains instructions that manipulate the memory and
Build Pipeline processor directly. It works on .i files and produces .s files

P
Compilers
gcc and g++ • The Assembler translates the assembly program to binary machine language or object code. It
Build with GCC
works on .s files and produces .o files

N
C/C++ Dialects
C Dialects • The Linker links our program with the pre-compiled libraries for using their functions and
C++ Dialects
generates the executable binary. It works on .o (static library), .so (shared library or
Standard Library
C Std. Lib.
dynamically linked library), and .a (library archive) files and produces a.out file
C++ Std. Lib.
std File extensions mentioned here are for GCC running on Linux. These may vary on other OSs
Header Conventions
and for other compilers. Check the respective documentation for details. The build pipeline,
Tutorial Summary
however, would be the same.

Programming in Modern C++ Partha Pratim Das T02.7


Compilers

Tutorial T02 • The recommended compiler for the course is GCC, the GNU Compiler Collection - GNU
Project. To install it (with gdb, the debugger) on your system, follow:

L
Partha Pratim
Das
◦ Windows: How to install gdb in windows 10 on YoutTube

E
Tutorial Recap ◦ Linux: Usually comes bundled in Linux distribution. Check manual
Objectives &
• You may also use online versions for quick tasks

T
Outline

Build Pipeline
◦ GNU Online Compiler

P
Compilers
gcc and g++ . From Language Drop-down, choose C (C99), C++ (C++11), C++14, or C++17
Build with GCC . To mark the language for gcc compilation, set -std=<compiler tag>

N
C/C++ Dialects
− Tags for C are: ansi, c89, c90, c11, c17, c18, etc.
C Dialects
C++ Dialects
− Tags for C++ are: ansi, c++98, c++03, c++11, c++14, c++17, c++20, etc.
Standard Library
− Check Options Controlling C Dialect and Language Standards Supported by GCC (Accessed
C Std. Lib. 13-Sep-21)
C++ Std. Lib.
std
◦ Code::Blocks is a free, open source cross-platform IDE that supports multiple compilers
Header Conventions including GCC, Clang and Visual C++
Tutorial Summary ◦ Programiz Online Compiler supports C18 and C++14
◦ OneCompiler supports C18 and C++17
• For a compiler, you must know the language version you are compiling for - check to confirm
Programming in Modern C++ Partha Pratim Das T02.8
What is GCC?

Tutorial T02

• GCC stands for GNU Compiler Collections which is used to compile mainly C and

L
Partha Pratim
Das
C++ language

E
Tutorial Recap
• It can also be used to compile Objective C, Objective C++, Fortran, Ada, Go, and D
Objectives &

T
Outline
• The most important option required while compiling a source code file is the name of
Build Pipeline
the source program, rest every argument is optional like a warning, debugging, linking

P
Compilers
gcc and g++ libraries, object file, etc.
Build with GCC

N
C/C++ Dialects • The different options of GCC command allow the user to stop the compilation process
C Dialects
C++ Dialects
at different stages.
Standard Library • g++ command is a GNU C++ compiler invocation command, which is used for
C Std. Lib.
C++ Std. Lib.
preprocessing, compilation, assembly and linking of source code to generate an
std executable file. The different “options” of g++ command allow us to stop this process
Header Conventions

Tutorial Summary
at the intermediate stage.

Programming in Modern C++ Partha Pratim Das T02.9


What are the differences between gcc and g++?

Tutorial T02
g++ gcc

L
Partha Pratim
Das g++ is used to compile C++ program gcc is used to compile C program
g++ can compile any .c or .cpp files but they gcc can compile any .c or .cpp files but they will

E
Tutorial Recap
will be treated as C++ files only be treated as C and C++ respectively
Objectives & Command to compile C++ program by g++ is: Command to compile C program by gcc is:

T
Outline
g++ fileName.cpp -o binary gcc fileName.c -o binary -lstdc++
Build Pipeline
Using g++ to link the object files, files automat- gcc does not do this and we need to specify

P
Compilers
gcc and g++ ically links in the std C++ libraries. -lstdc++ in the command line
Build with GCC g++ compiling .c/.cpp files has a few extra gcc compiling .c files has less predefined macros.

N
C/C++ Dialects macros gcc compiling .cpp files has a few extra macros
C Dialects
C++ Dialects
#define GXX WEAK 1
Standard Library
#define cplusplus 1
C Std. Lib.
C++ Std. Lib.
#define DEPRECATED 1
std #define GNUG 4
Header Conventions
#define EXCEPTIONS 1
Tutorial Summary #define private extern extern

Programming in Modern C++ Partha Pratim Das T02.10


Build with GCC: Options

Tutorial T02 [1] Place the source (.c) and header (.h) files in current directory
11-09-2021 10:46 157 fact.c

L
Partha Pratim
Das
11-09-2021 10:47 124 fact.h
11-09-2021 10:47 263 main.c
[2]

E
Tutorial Recap Compile source files (.c) and generate object (.o) files using option “-c”. Note additions of files to directory
Objectives & $ gcc -c fact.c

T
Outline $ gcc -c main.c
Build Pipeline
11-09-2021 11:02 670 fact.o

P
Compilers
gcc and g++
11-09-2021 11:02 1,004 main.o
Build with GCC [3] Link object (.o) files and generate executable (.exe) file of preferred name (fact) using option “-o”. Note added

N
C/C++ Dialects
file to directory
C Dialects $ gcc fact.o main.o -o fact
C++ Dialects

Standard Library
11-09-2021 11:03 42,729 fact.exe
C Std. Lib. [4] Execute
C++ Std. Lib. $ fact
std Input n
Header Conventions
5
Tutorial Summary fact(5) = 120
[5] We can combine steps [2] and [3] to generate executable directly by compiling and linking source files in one
command
$ gcc fact.c main.c -o fact
Programming in Modern C++ Partha Pratim Das T02.11
Build with GCC: Options

Tutorial T02 [6] We can only compile and generate assembly language (.s) file using option “-S”
$ gcc -S fact.c main.c

L
Partha Pratim
Das
11-09-2021 11:34 519 fact.s

E
Tutorial Recap 11-09-2021 11:34 1,023 main.s
Objectives & [7] To stop after prepossessing use option “-E”. The output is generated in stdout (redirected here to cppout.c).

T
Outline
$ gcc -E fact.c main.c >cppout.c
Build Pipeline

P
Compilers
11-09-2021 11:32 21,155 cppout.c
gcc and g++
Build with GCC Note that CPP:

N
C/C++ Dialects • Produces a single file containing the source from all .c files
C Dialects • Includes all required header files (like fact.h, stdio.h) and strips off unnecessary codes present there
C++ Dialects • Strips off all comments
Standard Library
• Textually replaces all manifest constants and expands all macros
C Std. Lib. [8] We can know the version of the compiler
C++ Std. Lib.
std
$ gcc --version
Header Conventions
gcc (MinGW.org GCC-6.3.0-1) 6.3.0
Tutorial Summary
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Programming in Modern C++ Partha Pratim Das T02.12


Build with GCC: Options

Tutorial T02
[9] When we intend to debug our code with gdb we need to use “-g” option to tell GCC to emit extra information for

L
Partha Pratim
Das
use by a debugger
$ gcc -g fact.c main.c -o fact

E
Tutorial Recap

Objectives & [10] We should always compile keeping it clean of all warnings. This can be done by “-Wall” flag. For example if we

T
Outline
comment out f = fact(n); and try to build we get warning, w/o “-Wall”, it is silent
Build Pipeline
$ gcc -Wall main.c

P
Compilers
gcc and g++
Build with GCC
main.c: In function ’main’:

N
main.c:14:5: warning: ’f’ is used uninitialized in this function [-Wuninitialized]
C/C++ Dialects
printf("fact(%d) = %d\n", n, f);
C Dialects
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C++ Dialects

Standard Library $ gcc main.c


C Std. Lib.
C++ Std. Lib.
std With “-Werror”, all warnings are treated as errors and no output will be produced
Header Conventions

Tutorial Summary

Programming in Modern C++ Partha Pratim Das T02.13


Build with GCC: Options

Tutorial T02
[11] We can trace the commands being used by the compiler using option “-v”, that is, verbose mode

L
Partha Pratim
Das $ gcc -v fact.c main.c -o fact

E
Tutorial Recap Using built-in specs.
Objectives &
COLLECT_GCC=gcc

T
Outline COLLECT_LTO_WRAPPER=c:/mingw/bin/../libexec/gcc/mingw32/6.3.0/lto-wrapper.exe
Target: mingw32
Build Pipeline
[truncated]

P
Compilers
gcc and g++
Thread model: win32
Build with GCC gcc version 6.3.0 (MinGW.org GCC-6.3.0-1)

N
[truncated]
C/C++ Dialects
C Dialects
C++ Dialects

Standard Library
C Std. Lib.
C++ Std. Lib.
std
Header Conventions

Tutorial Summary

Programming in Modern C++ Partha Pratim Das T02.14


Build with GCC: Summary of Options and Extensions
• gcc options and file extensions. Note that .c is shown as a placeholder for user provided source files. A detailed
Tutorial T02
list of source file extensions are given in the next point

L
Partha Pratim
Das Option Behaviour Input Output
Extension Extension

E
Tutorial Recap
-c Compile or assemble the source files, but do not link .c, .s, .i .o
Objectives & -S Stop after the stage of compilation proper; do not assemble .c, .i .s

T
Outline
-E Stop after the preprocessing stage .c To stdout
Build Pipeline -o file Place the primary output in file file (a.out w/o -o) .c, .s, .i Default for OS

P
Compilers -v Print the commands executed to run the stages of compilation .c, .s, .i To stdout
gcc and g++
Build with GCC

N
Source file (user provided) extensions
C/C++ Dialects
C Dialects
C++ Dialects
Extension File Type Extension File Type
Standard Library .c C source code that .cpp, .cc, .cp, .cxx C++ source code that
C Std. Lib. must be preprocessed .CPP, .c++, .C must be preprocessed
C++ Std. Lib. .h C / C++ header file .H, .hp, .hxx, .hpp C++ header file
std .HPP, .h++, .tcc
Header Conventions .s Assembler code .S, .sx Assembler code that
Tutorial Summary must be preprocessed
* Varied extensions for C++ happened during its evolution due various adoption practices
* We are going to follow the extensions marked in red
Source: 3.1 Option Summary and 3.2 Options Controlling the Kind of Output Accessed 13-Sep-21

Programming in Modern C++ Partha Pratim Das T02.15


C / C++ Dialects

Tutorial T02

L
Partha Pratim
Das

E
Tutorial Recap

Objectives &

T
Outline

Build Pipeline

P
Compilers
gcc and g++
Build with GCC

N
C/C++ Dialects
C Dialects
C++ Dialects

Standard Library
C Std. Lib.
C++ Std. Lib.
std
C / C++ Dialects
Header Conventions

Tutorial Summary

Programming in Modern C++ Partha Pratim Das T02.16


C Dialects

Tutorial T02

L
Partha Pratim
Das

E
Tutorial Recap

Objectives &

T
Outline

Build Pipeline

P
Compilers
gcc and g++
Build with GCC

N
C/C++ Dialects
C Dialects
C++ Dialects

Standard Library
C Std. Lib.
C++ Std. Lib.
std
Header Conventions

Tutorial Summary

Latest Version as of Sep-21: C18: ISO/IEC 9899:2018, 2018


Programming in Modern C++ Partha Pratim Das T02.17
C Dialects: Checking for a dialect

Tutorial T02 • We check the language version (dialect) of C being used by GCC in compilation using the following code
/* File Check C Version.c */

L
Partha Pratim
Das #include <stdio.h>
int main() {

E
Tutorial Recap if (__STDC_VERSION__ == 201710L) printf("C18\n"); /* C11 with bug fixes */
Objectives & else if (__STDC_VERSION__ == 201112L) printf("C11\n");

T
Outline else if (__STDC_VERSION__ == 199901L) printf("C99\n");
Build Pipeline
else if (__STDC_VERSION__ == 199409L) printf("C89\n");
else printf("Unrecognized version of C\n");

P
Compilers
gcc and g++
Build with GCC return 0;

N
}
C/C++ Dialects
C Dialects • We can ask GCC to use a specific dialect by using -std flag and check with the above code for three cases
C++ Dialects
$ gcc -std=c99 "Check C Version.c"
Standard Library C99
C Std. Lib.
C++ Std. Lib. $ gcc "Check C Version.c"
std C11
Header Conventions

Tutorial Summary $ gcc -std=c11 "Check C Version.c"


C11

Default for this gcc is C11


Programming in Modern C++ Partha Pratim Das T02.18
C++ Standards

Tutorial T02

L
Partha Pratim
Das

E
Tutorial Recap

Objectives &

T
Outline

Build Pipeline

P
Compilers
gcc and g++
Build with GCC

N
C/C++ Dialects
C Dialects
C++ Dialects

Standard Library
C Std. Lib.
C++ Std. Lib.
std
Header Conventions

Tutorial Summary

Fixes on C++98: C++03: ISO/IEC 14882:2003, 2003


Latest Version as of Sep-21: C++20: ISO/IEC 14882:2020, 2020
Programming in Modern C++ Partha Pratim Das T02.19
C++ Dialects: Checking for a dialect

Tutorial T02
• We check the language version (dialect) of C++ being used by GCC in compilation using the following code
// File Check C++ Version.cpp

L
Partha Pratim
Das
#include <iostream>
int main() {

E
Tutorial Recap if (__cplusplus == 201703L) std::cout << "C++17\n";
else if (__cplusplus == 201402L) std::cout << "C++14\n";
Objectives &
else if (__cplusplus == 201103L) std::cout << "C++11\n";

T
Outline
else if (__cplusplus == 199711L) std::cout << "C++98\n";
Build Pipeline else std::cout << "Unrecognized version of C++\n";

P
Compilers
return 0;
gcc and g++
}
Build with GCC

N
We can ask GCC to use a specific dialect by using -std flag and check with the above code for four cases
C/C++ Dialects
C Dialects $ g++ -std=gnu++98 "Check C++ Version.cpp"
C++ Dialects C++98
Standard Library
C Std. Lib.
$ g++ -std=c++11 "Check C++ Version.cpp"
C++ Std. Lib.
C++11
std
Header Conventions $ g++ -std=c++14 "Check C++ Version.cpp"
Tutorial Summary
C++14

$ g++ "Check C++ Version.cpp"


C++14
Default for this g++ is C++14
Programming in Modern C++ Partha Pratim Das T02.20
Standard Library

Tutorial T02

L
Partha Pratim
Das

E
Tutorial Recap

Objectives &

T
Outline

Build Pipeline

P
Compilers
gcc and g++
Build with GCC

N
C/C++ Dialects
C Dialects
C++ Dialects

Standard Library
C Std. Lib.
C++ Std. Lib.
std
Standard Library
Header Conventions

Tutorial Summary

Programming in Modern C++ Partha Pratim Das T02.21


What is Standard Library?

Tutorial T02 • A standard library in programming is the library made available across implementations of a
language

L
Partha Pratim
Das
• These libraries are usually described in language specifications (C/C++); however, they may

E
Tutorial Recap also be determined (in part or whole) by informal practices of a language’s community (Python)
Objectives & • A language’s standard library is often treated as part of the language by its users, although the

T
Outline
designers may have treated it as a separate entity
Build Pipeline
• Many language specifications define a core set that must be made available in all

P
Compilers
gcc and g++ implementations, in addition to other portions which may be optionally implemented
Build with GCC
• The line between a language and its libraries therefore differs from language to language

N
C/C++ Dialects
C Dialects
• Bjarne Stroustrup, designer of C++, writes:
C++ Dialects What ought to be in the standard C++ library? One ideal is for a programmer to be able to find every
Standard Library interesting, significant, and reasonably general class, function, template, etc., in a library. However, the question
C Std. Lib.
here is not, ”What ought to be in some library?” but ”What ought to be in the standard library?” The answer
C++ Std. Lib. ”Everything!” is a reasonable first approximation to an answer to the former question but not the latter. A
std standard library is something every implementer must supply so that every programmer can rely on it.
Header Conventions
• This suggests a relatively small standard library, containing only the constructs that “every
Tutorial Summary
programmer” might reasonably require when building a large collection of software
• This is the philosophy that is used in the C and C++ standard libraries
Source: Standard library, Wiki Accessed 13-Sep-21
Programming in Modern C++ Partha Pratim Das T02.22
C Standard Library: Common Library Components

Tutorial T02 Component Data Types, Manifest Constants, Macros, Functions, ...
Formatted and un-formatted file input and output including functions

L
Partha Pratim stdio.h
Das
• printf, scanf, fprintf, fscanf, sprintf, sscanf, feof, etc.

E
Tutorial Recap
stdlib.h Memory allocation, process control, conversions, pseudo-random numbers, search-
Objectives &
ing, sorting

T
Outline

Build Pipeline
• malloc, free, exit, abort, atoi, strtold, rand, bsearch, qsort, etc.

P
Compilers string.h Manipulation of C strings and arrays
gcc and g++
Build with GCC
• strcat, strcpy, strcmp, strlen, strtok, memcpy, memmove, etc.

N
C/C++ Dialects math.h Common mathematical operations and transformations
C Dialects • cos, sin, tan, acos, asin, atan, exp, log, pow, sqrt, etc.
C++ Dialects
errno.h Macros for reporting and retrieving error conditions through error codes stored in
Standard Library
C Std. Lib. a static memory location called errno
C++ Std. Lib. • EDOM (parameter outside a function’s domain – sqrt(-1)),
std
Header Conventions • ERANGE (result outside a function’s range), or
Tutorial Summary • EILSEQ (an illegal byte sequence), etc.
A header file typically contains manifest constants, macros, necessary struct / union types,
typedef’s, function prototype, etc.
Programming in Modern C++ Partha Pratim Das T02.23
C Standard Library: math.h
/* math.h
Tutorial T02
* This file has no copyright assigned and is placed in the Public Domain.
* This file is a part of the mingw-runtime package.

L
Partha Pratim
Das * Mathematical functions.
*/

E
Tutorial Recap
#ifndef _MATH_H_
Objectives & #define _MATH_H_

T
Outline #ifndef __STRICT_ANSI__ // conditional exclusions for ANSI
Build Pipeline // ...

P
Compilers #define M_PI 3.14159265358979323846 // manifest constant for pi
gcc and g++ // ...
Build with GCC struct _complex { // struct of _complex type

N
C/C++ Dialects double x; /* Real part */
C Dialects double y; /* Imaginary part */
C++ Dialects };
Standard Library
_CRTIMP double __cdecl _cabs (struct _complex); // cabs(.) function header
C Std. Lib.
// ...
C++ Std. Lib.
#endif /* __STRICT_ANSI__ */
std // ...
Header Conventions _CRTIMP double __cdecl sqrt (double); // sqrt(.) function header
Tutorial Summary
// ...
#define isfinite(x) ((fpclassify(x) & FP_NAN) == 0) // macro isfinite(.) to check if a number is finite
// ...
#endif /* _MATH_H_ */
Source: C math.h library functions Accessed 13-Sep-21
Programming in Modern C++ Partha Pratim Das T02.24
C++ Standard Library: Common Library Components

Tutorial T02 Component Data Types, Manifest Constants, Macros, Functions, Classes, ...
Stream input and output for standard I/O

L
Partha Pratim iostream
Das
• cout, cin, endl, ..., etc.

E
Tutorial Recap
string Manipulation of string objects
Objectives &
• Relational operators, IO operators, Iterators, etc.

T
Outline

Build Pipeline
memory High-level memory management

P
Compilers • Pointers: unique ptr, shared ptr, weak ptr, auto ptr, & allocator etc.
gcc and g++
Build with GCC
exception Generic Error Handling • exception, bad exception, unexpected handler,

N
C/C++ Dialects terminate handler, etc.
C Dialects stdexcept Standard Error Handling • logic error, invalid argument, domain error,
C++ Dialects
length error, out of range, runtime error, range error, overflow error,
Standard Library
C Std. Lib.
underflow error, etc.
C++ Std. Lib. Adopted from C Standard Library
std
Header Conventions cmath Common mathematical operations and transformations
Tutorial Summary • cos, sin, tan, acos, asin, atan, exp, log, pow, sqrt, etc.
cstdlib Memory alloc., process control, conversions, pseudo-rand nos., searching, sorting
• malloc, free, exit, abort, atoi, strtold, rand, bsearch, qsort, etc.
Programming in Modern C++ Partha Pratim Das T02.25
namespace std for C++ Standard Library

Tutorial T02
C Standard Library C++ Standard Library

L
Partha Pratim
Das
• All names are global • All names are within std namespace

E
Tutorial Recap • stdout, stdin, printf, scanf • std::cout, std::cin
Objectives & • Use using namespace std;

T
Outline

Build Pipeline to get rid of writing std:: for every standard

P
Compilers
library name
gcc and g++
Build with GCC
W/o using W/ using

N
C/C++ Dialects #include <iostream> #include <iostream>
C Dialects using namespace std;
C++ Dialects

Standard Library
int main() { int main() {
C Std. Lib.
C++ Std. Lib.
std std::cout << "Hello World in C++" cout << "Hello World in C++"
Header Conventions
<< std::endl; << endl;
Tutorial Summary

return 0; return 0;
} }

Programming in Modern C++ Partha Pratim Das T02.26


Standard Library: C/C++ Header Conventions

Tutorial T02 C Header C++ Header


C Program Use .h. Example: #include <stdio.h> Not applicable

L
Partha Pratim
Das Names in global namespace
C++ Program Prefix c, no .h. Example: #include <cstdio> No .h. Example:

E
Tutorial Recap
Names in std namespace #include <iostream>
Objectives &

T
Outline

Build Pipeline
• A C std. library header is used in C++ with prefix ’c’ and without the .h. These are in std namespace:

P
Compilers
#include <cmath> // In C it is <math.h>
gcc and g++
Build with GCC
...

N
C/C++ Dialects
std::sqrt(5.0); // Use with std::
C Dialects
C++ Dialects
It is possible that a C++ program include a C header as in C. Like:
Standard Library #include <math.h> // Not in std namespace
C Std. Lib. ...
C++ Std. Lib.
std
sqrt(5.0); // Use without std::
Header Conventions
This, however, is not preferred
Tutorial Summary
• Using .h with C++ header files, like iostream.h, is disastrous. These are deprecated. It is
dangerous, yet true, that some compilers do not error out on such use. Exercise caution.

Programming in Modern C++ Partha Pratim Das T02.27


Tutorial Summary

Tutorial T02

• Understood the overall build process for a C/C++ project with specific reference to the

L
Partha Pratim
Das
build pipeline of GCC

E
Tutorial Recap
• Understood the management of C/C++ dialects and C/C++ Standard Libraries
Objectives &

T
Outline

Build Pipeline

P
Compilers
gcc and g++
Build with GCC

N
C/C++ Dialects
C Dialects
C++ Dialects

Standard Library
C Std. Lib.
C++ Std. Lib.
std
Header Conventions

Tutorial Summary

Programming in Modern C++ Partha Pratim Das T02.28

You might also like