C++ Modules
C++ Modules
Partha Pratim
Das Module 01: Programming in C++
Objectives & Recap of C
Outline
Recap of C
Data Types
Variables
Literals Partha Pratim Das
Operators
Expressions
Statements Department of Computer Science and Engineering
Control Flow
Arrays Indian Institute of Technology, Kharagpur
Structures
Unions [email protected]
Pointers
Functions
Input / Output
Std Library
Tanwi Mallick
Srijoni Majumdar
Organization
Himadri B G S Bhuyan
Build Process
References
Module 01
Std Library
Organization
Build Process
References
Std Library
Organization
Build Process
References
Module 01
Std Library
Organization
Build Process
References
Module 01
Data types in C are used for declaring variables and deciding on
Partha Pratim
Das
storage and computations:
Objectives & Built-in / Basic data types are used to define raw data
Outline
char
Recap of C
Data Types int
Variables
Literals
float
Operators
Expressions
double
Statements
Control Flow Additionally, C99 defines:
Arrays
Structures
Unions
bool
Pointers
Functions All data items of a given type has the same size (in bytes). The
Input / Output
size is implementation-defined.
Std Library
Organization Enumerated Type data are internally of int type and operates
Build Process on a select subset.
References
Objectives &
Each variable in C has a specific type, which determines
Outline the size and layout of the storage (memory) for the variable
Recap of C The name of a variable can be composed of letters, digits,
Data Types
Variables and the underscore character. It must begin with either a
Literals
Operators
letter or an underscore
Expressions
Statements
Control Flow int i, j, noOfData;
Arrays
Structures char c, endOfSession;
Unions
Pointers float f, velocity;
Functions
Input / Output
double d, dist_in_light_years;
Std Library
Organization
Build Process
References
Recap of C
int i = 10, j = 20, numberOfWorkDays = 22;
Data Types char c = ’x’;
Variables
Literals float weight = 4.5;
Operators
Expressions
double density = 0.0;
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output
Std Library
Organization
Build Process
References
Module 01
Build Process
References
References
Recap of C
(of appropriate arity) is an expression
Data Types A function call is an expression
Variables
Literals
Operators
Examples:
Expressions
Statements For
Control Flow int i = 10, j = 20, k;
Arrays int f(int x, int y) { return x + y; }
Structures
Unions Expression are:
Pointers 2.5 // Value = 2.5
Functions i // Value 10
Input / Output -i // Value -10
Std Library i - j // Value -10
k = 5 // Value 5
Organization f(i, j) // Value 30
i + j == i * 3 // Value true
Build Process (i == j)? 1: 2 // Value 2
References
Build Process t = i;
i = j;
References j = t;
}
Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 14
Control Constructs
Recap of C
Iteration-statement: for, while, do-while
Data Types Jump-statement: goto, continue, break, return
Variables
Literals
Operators
Examples:
Expressions if (a < b) { if (x < 5) switch (i) {
Statements int t; x = x + 1; case 1: x = 5;
Control Flow else { break;
Arrays t = a; x = x + 2; case 3: x = 10;
Structures a = b; --y; default: x = 15;
Unions b = t; } }
Pointers
}
Functions
Input / Output
Std Library
Organization
Build Process
References
Std Library
Organization
Build Process
References
Module 01 A union is a special structure that allocates memory only for the
Partha Pratim
largest data member and holds only one member as a time
Das Declare Union:
typedef union _Packet { // Mixed Data Packet
int iData; // integer data
Objectives &
double dData; // floating point data
Outline
char cData; // character data
Recap of C } Packet;
Data Types
printf("size = %d\n", sizeof(Packet)); // Prints: size = 8
Variables
Literals
Operators
Initialize Union:
Expressions Packer p = {10}; // Initialize only with a value of the type of first member
Statements printf("iData = %d\n", p.iData); // Prints: iData = 10
Control Flow
Arrays
Structures Access Union members:
Unions p.iData = 2;
Pointers printf("iData = %d\n", p.iData); // Prints: iData = 2
Functions
p.dData = 2.2;
Input / Output
printf("dData = %lf\n", p.dData); // Prints: dData = 2.200000
Std Library p.cData = ’a’;
printf("cData = %c\n", p.cData); // Prints: cData = a
Organization
p.iData = 97;
Build Process printf("iData = %d\n", p.iData); // Prints: iData = 97
printf("dData = %lf\n", p.dData); // Prints: dData = 2.199999
References printf("cData = %c\n", p.cData); // Prints: cData = a
Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 20
Pointers
References
Module 01
• Pointer-Array Duality • Pointer to a structure
Partha Pratim int a[] = {1, 2, 3, 4, 5}; struct Complex { // Complex Number
Das int *p; double re; // Real component
double im; // Imaginary component
p = a; } c = { 0.0, 0.0 };
Objectives &
printf("a[0] = %d\n", *p); // a[0] = 1
Outline
printf("a[1] = %d\n", *++p); // a[1] = 2 struct Complex *p = &c;
Recap of C printf("a[2] = %d\n", *(p+1)); // a[2] = 3
(*p).re = 2.5;
Data Types
p = &a[2]; p->im = 3.6;
Variables
Literals *p = -10;
Operators printf("a[2] = %d\n", a[2]); // a[2] = -10 printf("re = %lf\n", c.re); // re = 2.500000
Expressions printf("im = %lf\n", c.im); // im = 3.600000
Statements
Control Flow
Arrays • malloc-free • Dynamically allocated arrays
Structures
int *p = (int *)malloc(sizeof(int)); int *p = (int *)malloc(sizeof(int)*3);
Unions
Pointers
Functions
*p = 0x8F7E1A2B; p[0] = 1; p[1] = 2; p[2] = 3;
Input / Output printf("%X\n", *p); // 8F7E1A2B
printf("p[1] = %d\n", *(p+1)); // p[1] = 2
Std Library unsigned char *q = p; free(p);
printf("%X\n", *q++); // 2B
Organization printf("%X\n", *q++); // 1A
printf("%X\n", *q++); // 7E
Build Process
printf("%X\n", *q++); // 8F
References
free(p);
Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 22
Module 01: End of Lecture 02
Std Library
Organization
Build Process
References
Std Library
Organization
Build Process
References
References
References return 0;
}
Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 26
Functions
References
Organization
Circle: (2.300000, 3.600000, 1.200000)
Build Process Rect: (4.500000, 1.900000, 4.200000, 3.800000)
Triag: (3.100000, 2.800000, 4.400000, 2.700000)
References
References
Module 01
To write to or read from file:
Partha Pratim #include <stdio.h>
Das
int main() {
Std Library
Organization
Build Process
References
Partha Pratim
Das Component Data Types, Manifest Constants, Macros, Functions, ...
stdio.h Formatted and un-formatted file input and output including
Objectives & functions
Outline
• printf, scanf, fprintf, fscanf, sprintf, sscanf, feof,
Recap of C etc.
Data Types
Variables
stdlib.h Memory allocation, process control, conversions, pseudo-
Literals random numbers, searching, sorting
Operators
Expressions
• malloc, free, exit, abort, atoi, strtold, rand,
Statements bsearch, qsort, etc.
Control Flow
string.h Manipulation of C strings and arrays
Arrays
Structures • strcat, strcpy, strcmp, strlen, strtok, memcpy,
Unions memmove, etc.
Pointers
Functions math.h Common mathematical operations and transformations
Input / Output • cos, sin, tan, acos, asin, atan, exp, log, pow, sqrt, etc.
Std Library errno.h Macros for reporting and retrieving error conditions through
Organization
error codes stored in a static memory location called errno
• EDOM (parameter outside a function’s domain – sqrt(-1)),
Build Process • ERANGE (result outside a function’s range), or
References • EILSEQ (an illegal byte sequence), etc.
Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 31
Source Organization for a C program
Module 01
Header Files
Partha Pratim
Das A header file has extension .h and contains C function
Objectives & declarations and macro definitions to be shared between several
Outline source files
Recap of C
Data Types There are two types of header files:
Variables
Literals
Operators
Files that the programmer writes
Expressions
Statements
Files from standard library
Control Flow
Arrays Header files are included using the #include pre-processing
Structures
Unions directive
Pointers
Functions
Input / Output
#include <file> for system header files
Std Library
#include "file" for header files of your own program
Organization
Build Process
References
Module 01
Partha Pratim
Example:
Das
// Solver.h -- Header files
int quadraticEquationSolver(double, double, double, double*, double*);
Objectives &
Outline // Solver.c -- Implementation files
#include "Solver.h"
Recap of C
Data Types int quadraticEquationSolver(double a, double b, doublec , double* r1, double* r2) {
Variables // ...
Literals // ...
Operators // ...
Expressions
return 0;
Statements
}
Control Flow
Arrays
Structures
// main.c -- Application files
Unions
#include "Solver.h"
Pointers
Functions int main() {
Input / Output double a, b, c;
double r1, r2;
Std Library
int status = quadraticEquationSolver(a, b, c, &r1, &r2);
Organization
return 0;
Build Process
}
References
Module 01
Partha Pratim
Das
Objectives &
Outline
Recap of C
Data Types
Variables
Literals
Operators
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output
Std Library
Organization
Build Process
References
Module 01
C Pre-processor (CPP) substitutes and includes functions,
Partha Pratim
Das headers and macros before compilation
int sum(int, int);
Objectives & int main() {
Outline int a = sum(1,2);
return a;
Recap of C }
Data Types
Variables
Literals The compiler translates the pre-processed C code into assembly
Operators
Expressions
language, which is a machine level code that contains
Statements
Control Flow
instructions that manipulate the memory and processor directly
Arrays
Structures The linker links our program with the pre-compiled libraries for
Unions
Pointers
using their functions
Functions
Input / Output In the running example, function.c and main.c are first
Std Library
compiled and then linked
Organization int sum(int a,int b) { return a+b; }
Module 01
Recap of C
Data Types
Variables
Literals
Operators
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output
Std Library
Organization
Build Process
References
Module 01
Partha Pratim
Das Kernighan, Brian W., and Dennis M. Richie. The C
Programming Language. Vol. 2. Englewood Cliffs:
Objectives &
Outline Prentice-Hall, 1988.
Recap of C
Data Types
King, Kim N., and Kim King. C programming: A Modern
Variables
Literals
Approach. Norton, 1996.
Operators
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output
Std Library
Organization
Build Process
References
Module 01
Std Library
Organization
Build Process
References
Module 01
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Recap of C
Srijoni Majumdar, TA [email protected] 9674474267
Data Types Himadri B G S Bhuyan, TA [email protected] 9438911655
Variables
Literals
Operators
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output
Std Library
Organization
Build Process
References
Partha Pratim
Das Module 02: Programming in C++
Objectives & Programs with IO & Loop
Outline
Hello World
Add numbers
Square Root
Standard Library
Sum Numbers Partha Pratim Das
Using bool
Summary
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 02
Summary
Module 02
printf("Sq. Root of %lf is:", x); cout << "Sq. Root of " << x;
printf(" %lf\n", sqrt_x); cout << " is: " << sqrt_x << endl;
return 0; return 0;
} }
Input number: Input number:
2 2
Square Root of 2.000000 is: 1.414214 Square Root of 2 is: 1.41421
• Math Header is math.h (C Standard Library) • Math Header is cmath (C Standard Library in C++)
• Formatting (%lf) needed for variables • Formatting is derived from type (double) of variables
• sqrt function from C Standard Library • sqrt function from C Standard Library
• Default precision in print is 6 • Default precision in print is 5 (different)
Partha Pratim • All names are global • All names are within std namespace
Das
• stdout, stdin, printf, scanf • std::cout, std::cin
Objectives &
• Use
Outline
Hello World using namespace std;
Add numbers
Square Root
to get rid of writing std:: for every standard
Standard Library
library name
Sum Numbers
Using bool
std::cout << "Hello World in C++" cout << "Hello World in C++"
<< std::endl; << endl;
return 0; return 0;
} }
Module 02
Summary for (i = 0; i <= n; ++i) for (int i = 0; i <= n; ++i) // Local Decl.
sum = sum + i; sum = sum + i;
return 0; return 0;
} }
• Using int and #define for bool • stdbool.h included for bool • No additional headers required
• May use Bool (C99) • Bool type & macros (C99):
bool which expands to Bool bool is a built-in type
true which expands to 1 true is a literal
false which expands to 0 false is a literal
Module 02
Module 02
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Hello World Srijoni Majumdar, TA [email protected] 9674474267
Add numbers
Square Root Himadri B G S Bhuyan, TA [email protected] 9438911655
Standard Library
Sum Numbers
Using bool
Summary
Partha Pratim
Das Module 03: Programming in C++
Objectives & Arrays and Strings
Outline
Arrays &
Vectors
Fixed Size Array
Arbitrary Size Partha Pratim Das
Array
Vectors
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 03
Strings
Summary
Module 03
23 34 65 74 23 34 65 74
Module 03
This can be implemented in C (C++) in the following ways:
Partha Pratim
Das Case 1: Declaring a large array with size greater than the
Objectives &
size given by users in all (most) of the cases
Outline Hard-code the maximum size in code
Arrays &
Vectors
Declare a manifest constant for the maximum size
Fixed Size Array
Arbitrary Size
Case 2: Using malloc (new[]) to dynamically allocate
Array
Vectors space at run-time for the array
Strings
Summary
return 0; return 0;
} }
• MAX is the declared size of array • MAX is the declared size of vector
• No header needed • Header vector included
• arr declared as int [] • arr declared as vector<int>
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Program 03.04: Dynamically managed array size
• malloc allocates space using sizeof • resize fixes vector size at run-time
Module 03
String manipulations in C and C++:
Partha Pratim
Das C-String and string.h library
Objectives & C-String is an array of char terminated by NULL
Outline C-String is supported by functions in string.h in C
Arrays &
Vectors
standard library
Fixed Size Array
Arbitrary Size
string type in C++ standard library
Array
Vectors string is a type
Strings With operators (like + for concatenation) behaves like a
Summary built-in type
Module 03
Further,
Partha Pratim
Das operator= can be used on strings in place of strcpy
Objectives & function in C.
Outline
Arrays &
operator<=, operator<, operator>=, operator>
Vectors operators can be used on strings in place of strcmp
Fixed Size Array
Arbitrary Size
Array
function in C
Vectors
Strings
Summary
Module 03
Partha Pratim Working with variable sized arrays is more flexible with
Das
vectors in C++
Objectives &
Outline String operations are easier with C++ standard library
Arrays &
Vectors
Fixed Size Array
Arbitrary Size
Array
Vectors
Strings
Summary
Module 03
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Arrays &
Srijoni Majumdar, TA [email protected] 9674474267
Vectors Himadri B G S Bhuyan, TA [email protected] 9438911655
Fixed Size Array
Arbitrary Size
Array
Vectors
Strings
Summary
Partha Pratim
Das Module 04: Programming in C++
Objectives & Sorting and Searching
Outline
Sorting
Bubble Sort
Standard Library
Searching
Partha Pratim Das
Standard Library
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 04
Objectives &
Outline
Sorting
Bubble Sort
Standard Library
Searching
Standard Library
STL:
algorithm
Summary
Module 04
STL:
algorithm
Summary
return 0; return 0;
} }
12 26 32 45 71 12 26 32 45 71
• Implementation is same in both C and C++ apart from the changes in basic header files, I/O functions
explained in Module 02.
STL: // Start ptr, # elements, size, func. ptr // Start ptr, end ptr, func. ptr
algorithm qsort(data, 5, sizeof(int), compare); sort (data, data+5, compare);
return 0; return 0;
} }
71 45 32 26 12 71 45 32 26 12
STL: return 0;
algorithm }
Summary 12 26 32 45 71
• Sort using the default sort function of algorithm library which does the sorting in ascending order only.
return 0; return 0;
} }
found! found!
Module 04
The algorithm library of c++ helps us to easily implement
Partha Pratim
Das commonly used complex functions. We discussed the functions
Objectives &
for sort and search. Let us look at some more useful functions.
Outline
Replace element in an array
Sorting
Bubble Sort
Standard Library
Rotates the order of the elements
Searching
Standard Library
STL:
algorithm
Summary
Summary
1 2 2 4 5 3 4 5 1 2
• 3rd element replaced with 2 • Array circular shifted around 3rd element.
Module 04
Summary
Module 04
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Sorting
Srijoni Majumdar, TA [email protected] 9674474267
Bubble Sort Himadri B G S Bhuyan, TA [email protected] 9438911655
Standard Library
Searching
Standard Library
STL:
algorithm
Summary
Partha Pratim
Das Module 05: Programming in C++
Objectives & Stack and its Applications
Outline
Stack in C
Reverse a String
Eval Postfix
Stack in C++
Partha Pratim Das
Reverse a String
Eval Postfix
Department of Computer Science and Engineering
Summary Indian Institute of Technology, Kharagpur
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 05
Stack in C
Reverse a String
Eval Postfix
Stack in C++
Reverse a String
Eval Postfix
Summary
Module 05
Summary
Module 05
Some common C programs that use stack:
Partha Pratim
Das Reversing a string
Objectives & Input: ABCDE
Outline Output: EDCBA
Stack in C
Reverse a String
Evaluation of postfix expression
Eval Postfix
Input: 1 2 3 * + 4 - (for 1 + 2 * 3 - 4)
Stack in C++
Reverse a String
Output: 3
Eval Postfix Stack states:
Summary
1 2 3 6 7 4 3
1 2 1 7
1
Evaluation 3
Module 05
Partha Pratim C++ standard library provide a ready-made stack for any
Das
type of elements
Objectives &
Outline
To create a stack in C++ we need to:
Stack in C Include the stack header
Reverse a String Instantiate a stack with proper element type (like char)
Eval Postfix
Stack in C++
Use the functions of the stack objects for stack operations
Reverse a String
Eval Postfix
Summary
return 0; return 0;
} }
Module 05 // FileName:Postfix_Evaluation_c++.cpp
#include <iostream>
Partha Pratim #include <stack>
Das using namespace std;
int main() {
Objectives & // Postfix expression: 1 2 3 * + 4 -
Outline char postfix[] = {’1’,’2’,’3’,’*’,’+’,’4’,’-’}, ch;
stack<int> s;
Stack in C
Reverse a String
for(int i = 0; i < 7; i++) {
Eval Postfix
ch = postfix[i];
Stack in C++ if (isdigit(ch)) { s.push(ch-’0’); }
Reverse a String else {
Eval Postfix int op1 = s.top(); s.pop();
int op2 = s.top(); s.pop();
Summary switch(ch) {
case ’*’: s.push(op2 * op1); break;
case ’/’: s.push(op2 / op1); break;
case ’+’: s.push(op2 + op1); break;
case ’-’: s.push(op2 - op1); break;
}
}
}
cout << "\nEvaluation " << s.top();
return 0;
}
Module 05
Module 05
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Stack in C
Srijoni Majumdar, TA [email protected] 9674474267
Reverse a String Himadri B G S Bhuyan, TA [email protected] 9438911655
Eval Postfix
Stack in C++
Reverse a String
Eval Postfix
Summary
Partha Pratim
Das
Module 06: Programming in C++
Objectives &
Outline
Constants and Inline Functions
const-ness &
cv-qualifier
const-ness
Advantages Partha Pratim Das
Pointers
volatile
inline
Department of Computer Science and Engineering
functions Indian Institute of Technology, Kharagpur
Macros
inline [email protected]
Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 06
inline
functions
Macros
inline
Summary
Module 06
The value of a const variable cannot be changed after definition
const int n = 10; // n is an int type variable with value 10
Partha Pratim // n is a constant
Das ...
n = 5; // Is a compilation error as n cannot be changed
Objectives & ...
Outline int m;
int *p = 0;
const-ness & p = &m; // Hold m by pointer p
cv-qualifier *p = 7; // Change m by p; m is now 7
const-ness ...
Advantages p = &n; // Is a compilation error as n may be changed by *p = 5;
Pointers
volatile
Naturally, a const variable must be initialized when defined
inline
functions const int n; // Is a compilation error as n must be initialized
Macros
inline
A variable of any data type can be declared as const
Summary
typedef struct _Complex {
double re;
double im;
} Complex;
const Complex c = {2.3, 7.5}; // c is a Complex type variable
// 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
NPTEL MOOCs Programming in C++ Partha Pratim Das 5
Program 06.02: Compare #define and const
Module 06
Natural Constants like π, e, Φ (Golden Ratio) etc. can be
compactly defined and used
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
Objectives &
Outline const int TRUE = 1; // Truth values
const int FALSE = 0;
const-ness &
cv-qualifier
const int null = 0; // null value
const-ness
Advantages
Pointers Note: NULL is a manifest constant in C/C++ set to 0.
volatile
inline Program Constants like number of elements, array size etc. can
functions be defined at one place (at times in a header) and used all over
Macros
inline the program
Summary const int nArraySize = 100;
const int nElements = 10;
int main() {
int A[nArraySize]; // Array size
for (int i = 0; i < nElements; ++i) // Number of elements
A[i] = i * i;
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Advantages of const
inline
functions
Macros
inline
Summary
Module 06 const-ness can be used with Pointers in one of the two ways:
Partha Pratim
Das
Pointer to Constant data where the pointee (pointed
data) cannot be changed
Objectives & Constant Pointer where the pointer (address) cannot be
Outline
const-ness &
changed
cv-qualifier
const-ness
Consider usual pointer-pointee computation (without const):
Advantages
Pointers int m = 4;
volatile int n = 5;
int * p = &n; // p points to n. *p is 5
inline ...
functions n = 6; // n and *p are 6 now
Macros *p = 7; // n and *p are 7 now. POINTEE changes
inline ...
Summary p = &m; // p points to m. *p is 4. POINTER changes
*p = 8; // m and *p are 8 now. n is 7. POINTEE changes
Module 06
Consider pointed data
Partha Pratim
Das int m = 4;
const int n = 5;
const int * p = &n;
Objectives & ...
Outline n = 6; // Error: n is constant and cannot be changed
*p = 7; // Error: p points to a constant data (n) that cannot be changed
const-ness & p = &m; // Okay
cv-qualifier *p = 8; // Okay
const-ness
Advantages
Pointers Interestingly,
volatile
inline int n = 5;
functions const int * p = &n;
...
Macros
n = 6; // Okay
inline
*p = 6; // Error: p points to a ’constant’ data (n) that cannot be changed
Summary
Finally,
const int n = 5;
int * p = &n; // Error: If this were allowed, we would be able to change constant n
...
n = 6; // Error: n is constant and cannot be changed
*p = 6; // Would have been okay, if declaration of p were valid
Module 06
Consider pointer
Partha Pratim int m = 4, n = 5;
Das int * const p = &n;
...
n = 6; // Okay
Objectives & *p = 7; // Okay. Both n and *p are 7 now
Outline ...
p = &m; // Error: p is a constant pointer and cannot be changed
const-ness &
cv-qualifier
const-ness By extension, both can be const
Advantages
Pointers const int m = 4;
volatile const int n = 5;
const int * const p = &n;
inline
...
functions
n = 6; // Error: n is constant and cannot be changed
Macros
*p = 7; // Error: p points to a ’constant’ data (n) that cannot be changed
inline
...
Summary p = &m; // Error: p is a constant pointer and cannot be changed
Module 06
Consider the example:
char * str = strdup("IIT, Kharagpur");
Partha Pratim str[0] = ’N’; // Edit the name
Das cout << str << endl;
str = strdup("JIT, Kharagpur"); // Change the name
Objectives & cout << str << endl;
Outline
Output is:
const-ness &
cv-qualifier NIT, Kharagpur
const-ness JIT, Kharagpur
Advantages
Pointers To stop editing the name:
volatile
const char * str = strdup("IIT, Kharagpur");
inline
str[0] = ’N’; // Error: Cannot Edit the name
functions
str = strdup("JIT, Kharagpur"); // Change the name
Macros
inline
To stop changing the name:
Summary
char * const str = strdup("IIT, Kharagpur");
str[0] = ’N’; // Edit the name
str = strdup("JIT, Kharagpur"); // Error: Cannot Change the name
To stop both:
const char * const str = strdup("IIT, Kharagpur");
str[0] = ’N’; // Error: Cannot Edit the name
str = strdup("JIT, Kharagpur"); // Error: Cannot Change the name
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Notion of volatile
Module 06
Consider:
Partha Pratim static int i;
Das void fun(void) {
i = 0;
while (i != 100);
Objectives & }
Outline
const-ness & This is an infinite loop! Hence the compiler should optimize as:
cv-qualifier
const-ness static int i;
Advantages void fun(void) {
Pointers i = 0;
volatile while (1); // Compiler optimizes
}
inline
functions
Macros Now qualify i as volatile:
inline
static volatile int i;
Summary
void fun(void) {
i = 0;
while (i != 100); // Compiler does not optimize
}
Square = 9 Square = 9
• 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
Module 06
Consider the example:
#include <iostream>
Partha Pratim
using namespace std;
Das
#define SQUARE(x) x * x
Objectives &
Outline int main() {
int a = 3, b;
const-ness &
cv-qualifier b = SQUARE(a + 1); // Wrong macro expansion
const-ness
Advantages cout << "Square = " << b << endl;
Pointers
volatile return 0;
}
inline
functions
Macros Output is 7 in stead of 16 as expected. On the expansion line it gets:
inline
b = a + 1 * a + 1;
Summary
To fix:
#define SQUARE(x) (x) * (x)
Now:
b = (a + 1) * (a + 1);
NPTEL MOOCs Programming in C++ Partha Pratim Das 16
Pitfalls of macros
Module 06
Continuing ...
Partha Pratim #include <iostream>
Das using namespace std;
Module 06
inline
functions
Macros
inline
Summary
Summary
Square = 9 Square = 9
• 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
• SQUARE(a + 1) fails • SQUARE(a + 1) works
• SQUARE(++a) fails • SQUARE(++a) works
• SQUARE(++a) does not check type • SQUARE(++a) checks type
Partha Pratim • Expanded at the place of calls • Expanded at the place of calls
Das • Efficient in execution • Efficient in execution
• Code bloats • Code bloats
• Has syntactic and semantic pitfalls • No pitfall
Objectives &
• Type checking for parameters is not done • Type checking for parameters is robust
Outline
• Helps to write max / swap for all types • Needs template for the same purpose
const-ness & • Errors are not checked during compilation • Errors are checked during compilation
cv-qualifier • Not available to debugger • Available to debugger in DEBUG build
const-ness
Advantages
Pointers
volatile
inline
functions
Macros
inline
Summary
Module 06
Summary
Module 06
Module 06
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
const-ness &
Srijoni Majumdar, TA [email protected] 9674474267
cv-qualifier Himadri B G S Bhuyan, TA [email protected] 9438911655
const-ness
Advantages
Pointers
volatile
inline
functions
Macros
inline
Summary
Partha Pratim
Das
Module 07: Programming in C++
Objectives &
Outlines
Reference & Pointer
Reference
variable
I/O of a
Function
Tanwi Mallick
References vs. Srijoni Majumdar
Pointers
Himadri B G S Bhuyan
Summary
Module 07
Reference
variable
Call-by-
reference
Swap in C
Swap in C++
const Reference
Parameter
Return-by-
reference
I/O of a
Function
References vs.
Pointers
Summary
Module 07
References vs.
Differences between References and Pointers
Pointers
Summary
Module 07
Call-by- i ← variable
reference
Swap in C 15 ← memory content
Swap in C++
const Reference
Parameter
200 ← address
Return-by- j ← alias or reference
reference
I/O of a
Function
References vs.
Pointers
Summary
Module 07
#include <iostream>
Partha Pratim using namespace std;
Das
int main() {
int a = 10, &b = a; // b is reference of a
Objectives &
Outlines // a and b have the same memory
cout << "a = " << a << ", b = " << b << endl;
Reference
cout << "&a = " << &a << ", &b = " << &b << endl;
variable
I/O of a a = 10, b = 10
Function &a = 002BF944, &b = 002BF944
a = 11, b = 11
References vs. a = 12, b = 12
Pointers
Summary • a and b have the same memory location and hence the same value
• Changing one changes the other and vice-versa
Partha Pratim
Das int& i; no variable to refer to – must be initialized int& i = j;
Call-by-
reference
Swap in C
Swap in C++
const Reference
Parameter
Return-by-
reference
I/O of a
Function
References vs.
Pointers
Summary
Return-by- const int& b = // const needed. Why? const int& b = // const optional
reference Function_Return_By_Val(a); Function_Return_By_Ref(a);
I/O of a cout <<"b = "<<b<<" &b = "<<&b<<endl; cout <<"b = "<<b<<" &b = "<<&b<<endl;
Function return 0; return 0;
} }
References vs.
Pointers a = 10 &a = 00DCFD18 a = 10 &a = 00A7F8FC
x = 10 &x = 00DCFD18 x = 10 &x = 00A7F8FC
Summary b = 10 &b = 00DCFD00 b = 10 &b = 00A7F8FC
Summary • Note how a value is assigned to function call • We expect a to be 3, but it has not changed
• This can change a local variable • It returns reference to local. This is risky
Call-by-
Return Value Output Return-by-value
reference Return-by-reference
Swap in C
Swap in C++
const Reference
Parameter
Return-by-
reference
I/O of a
Function
References vs.
Pointers
Summary
Module 07 Call
Partha Pratim
Pass parameters of built-in types by value
Das Recall: Array parameters are passed by reference in C
Objectives & Pass parameters of user-defined types by reference
Outlines
Make a reference parameter const if it is not used for
Reference output
variable
Call-by- Return
reference
Swap in C
Return built-in types by value
Swap in C++ Return user-defined types by reference
const Reference
Parameter Return value is not copied back
Return-by- May be faster than returning a value
reference
Beware: Calling function can change returned object
I/O of a
Function Never return a local variables by reference
References vs.
Pointers
Summary
Summary
Module 07
Return-by-
reference
I/O of a
Function
References vs.
Pointers
Summary
Module 07
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outlines Tanwi Mallick, TA [email protected] 9674277774
Reference
Srijoni Majumdar, TA [email protected] 9674474267
variable Himadri B G S Bhuyan, TA [email protected] 9438911655
Call-by-
reference
Swap in C
Swap in C++
const Reference
Parameter
Return-by-
reference
I/O of a
Function
References vs.
Pointers
Summary
Partha Pratim
Das Module 08: Programming C++
Objectives & Default Parameters & Function Overloading
Outline
Default
Parameter
Overload
Resolution Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur
Default
Parameters in [email protected]
Overloading
Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 08
Default
Parameter
Function
Overloading
Overload
Resolution
Default
Parameters in
Overloading
Summary
Module 08
Module 08
Module 08 #include<iostream>
using namespace std;
Partha Pratim
Das
int Add(int a = 10, int b = 20) {
Objectives & return (a + b);
Outline }
Default int main(){
Parameter int x = 5, y = 6, z;
Function
Overloading z = Add(x, y); // Usual function call -- a = x = 5 & b = y = 6
Overload
cout << "Sum = " << z << endl;
Resolution
Default
z = Add(x); // One parameter defaulted -- a = x = 5 & b = 20
Parameters in cout << "Sum = " << z << endl;
Overloading
Module 08
Summary
Summary g(); // Error C2660: ’g’: function does not take 0 arguments
g(i);
g(i, d);
g(i, d, &c);
return 0;
}
g(); // Prints: 0 0 a
g(i); // Prints: 5 0 a
g(i, d); // Prints: 5 1.2 a
g(i, d, c); // Prints: 5 1.2 b
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Function overloads: Matrix Multiplication in C
Similar functions with different data types & algorithms
Module 08
typedef struct { int data[10][10]; } Mat; // 2D Matrix
Partha Pratim typedef struct { int data[1][10]; } VecRow; // Row Vector
Das typedef struct { int data[10][1]; } VecCol; // Column Vector
Module 08
Functions having similar functionality but different in details.
Partha Pratim
Das typedef struct { int data[10][10]; } Mat; // 2D Matrix
typedef struct { int data[1][10]; } VecRow; // Row Vector
Objectives & typedef struct { int data[10][1]; } VecCol; // Column Vector
Outline
void Multiply(const Mat& a, const Mat& b, Mat& c) { /* c = a * b */ };
Default void Multiply(const Mat& a, const VecCol& b, VecCol& c) { /* c = a * b */ };
Parameter void Multiply(const VecRow& a, const Mat& b, VecRow& c) { /* c = a * b */ };
void Multiply(const VecCol& a, const VecRow& b, Mat& c) { /* c = a * b */ };
Function void Multiply(const VecRow& a, const VecCol& b, int& c) { /* c = a * b */ };
Overloading
int main() {
Overload
Mat m1, m2, rm; VecRow rv, rrv; VecCol cv, rcv; int r;
Resolution
Multiply(m1, m2, rm); // rm <-- m1 * m2
Default Multiply(m1, cv, rcv); // rcv <-- m1 * cv
Parameters in Multiply(rv, m2, rrv); // rrv <-- rv * m2
Overloading Multiply(cv, rv, rm); // rm <-- cv * rv
Multiply(rv, cv, r); // r <-- rv * cv
Summary return 0;
}
return 0; return 0;
} }
return 0;
}
Module 08
Summary
Module 08
Module 08
Summary Resolution:
Candidate functions (by name): F2, F3, F6, F8
Viable functions (by # of parameters): F3, F6
Best viable function (by type double – Exact Match): F6
Module 08
• Consider the overloaded function signatures:
Partha Pratim
Das int fun(float a) {...} // Function 1
int fun(float a, int b) {...} // Function 2
Objectives & int fun(float x, int y = 5) {...} // Function 3
Outline
Summary
• CALL - 1: Matches Function 2 & Function 3
• CALL - 2: Matches Function 1 & Function 3
• Results in ambiguity
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 21
Program 08.09:
Default Parameter & Function Overload
Module 08 Function overloading with default parameters may fail
Partha Pratim
Das #include <iostream>
using namespace std;
Objectives & int f();
Outline int f(int = 0);
Default int f(int, int);
Parameter
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 22
Module Summary
Module 08
Summary
Module 08
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Default
Srijoni Majumdar, TA [email protected] 9674474267
Parameter Himadri B G S Bhuyan, TA [email protected] 9438911655
Function
Overloading
Overload
Resolution
Default
Parameters in
Overloading
Summary
Partha Pratim
Das Module 09: Programming in C++
Objectives & Operator Overloading
Outline
Operators &
Functions
Examples
String
Department of Computer Science and Engineering
Enum Indian Institute of Technology, Kharagpur
Operator
Overloading
[email protected]
Rules
Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 09
Objectives &
Outline
Operators &
Functions
Operator
Overloading
Examples
String
Enum
Operator
Overloading
Rules
Summary
Module 09
Examples
String
Enum
Operator
Overloading
Rules
Summary
return 0;
}
Module 09
Operator Function
Partha Pratim
Das
• Usually written in infix nota- • Always written in prefix no-
Objectives & tion tation
Outline
• Examples: • Examples:
Operators & Infix: a + b; a ? b : c; Prefix: max(a, b);
Functions
Prefix: ++a; qsort(int[], int, int,
Operator Postfix: a++; void (*)(void*, void*));
Overloading
• Operates on one or more • Operates on zero or more ar-
Examples
String
operands, typically up to 3 guments
Enum (Unary, Binary or Ternary)
Operator • Produces one result • Produces up to one result
Overloading
Rules • Order of operations is de- • Order of application is de-
Summary cided by precedence and asso- cided by depth of nesting
ciativity
• Operators are pre-defined • Functions can be defined as
needed
a + b // Calls operator+(a, b)
Examples x = a + b; x = a + b;
String cout << x << endl; cout << x << endl;
Enum
return 0; return 0;
Operator } }
Overloading ---------- ----------
Rules 3 0
Summary • Implicitly converts enum E values to int
• Adds by operator+ of int • operator + is overloaded for enum E
• Result is outside enum E range • Result is a valid enum E value
Module 09
No new operator such as **, <>, or &| can be defined for overloading
Partha Pratim
Das
Intrinsic properties of the overloaded operator cannot be change
Objectives & Preserves arity
Outline Preserves precedence
Operators & Preserves associativity
Functions
These operators can be overloaded:
Operator
Overloading [] + - * / % & | ~ ! = += -= *= /= %= = &= |=
<< >> >>= <<= == != < > <= >= && || ++ -- , ->* -> ( ) [ ]
Examples
String For unary prefix operators, use: MyType& operator++(MyType& s1)
Enum
For unary postfix operators, use: MyType operator++(MyType& s1, int)
Operator
Overloading The operators :: (scope resolution), . (member access), .* (member access
Rules through pointer to member), sizeof, and ?: (ternary conditional) cannot
Summary be overloaded
The overloads of operators &&, ||, and , (comma) lose their special
properties: short-circuit evaluation and sequencing
The overload of operator-> must either return a raw pointer or return an
object (by reference or by value), for which operator-> is in turn overloaded
Module 09
Operators &
Functions
Operator
Overloading
Examples
String
Enum
Operator
Overloading
Rules
Summary
Module 09
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Operators &
Srijoni Majumdar, TA [email protected] 9674474267
Functions Himadri B G S Bhuyan, TA [email protected] 9438911655
Operator
Overloading
Examples
String
Enum
Operator
Overloading
Rules
Summary
Partha Pratim
Das Module 10: Programming in C++
Objectives & Dynamic Memory Management
Outline
Memory
Management
in C
malloc & free Partha Pratim Das
Memory
Management
in C++
Department of Computer Science and Engineering
new & delete Indian Institute of Technology, Kharagpur
Array
Placement new [email protected]
Restrictions
Overloading
new & delete Tanwi Mallick
Summary Srijoni Majumdar
Himadri B G S Bhuyan
Module 10
Objectives &
Outline
Memory
Management
in C
malloc & free
Memory
Management
in C++
new & delete
Array
Placement new
Restrictions
Overloading
new & delete
Summary
Module 10
Overloading
new & delete
Summary
Overloading
malloc() allocates the memory on heap
new & delete sizeof(int) needs to be provided
Summary Pointer to allocated memory returned as void * – needs cast to int *
Allocated memory is released by free() from heap
calloc() and realloc() also available in both languages
There is a major difference between operator new and function operator new(). We explore this
angle more after we learn about classes
Memory
Allocator De-allocator
Management malloc() free()
in C
malloc & free operator new operator delete
Memory operator new[] operator delete[]
Management
in C++ operator new() No delete
new & delete
Array
Placement new
Restrictions Passing NULL pointer to delete operator is secure
Overloading
new & delete
Prefer to use only new and delete in a C++ program
Summary The new operator allocates exact amount of memory from Heap
new returns the given pointer type – no need to typecast
new, new[ ] and delete, delete[] have separate semantics
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Program 10.08: Overloading operator new
Module 10
#include <iostream>
Partha Pratim #include <stdlib.h>
Das using namespace std;
Overloading delete [] t;
new & delete return 0; • operator new[] overloaded with initialization
} • The first parameter of overloaded operator new[] must be size t
Summary ----- • The return type of overloaded operator new[] must be void *
p = 19421992 • Multiple parameters may be used for overloading
########## • operator delete [] should not be overloaded (usually) with
extra parameters
Module 10
Overloading
new & delete
Summary
Module 10
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Memory
Srijoni Majumdar, TA [email protected] 9674474267
Management Himadri B G S Bhuyan, TA [email protected] 9438911655
in C
malloc & free
Memory
Management
in C++
new & delete
Array
Placement new
Restrictions
Overloading
new & delete
Summary
Partha Pratim
Das Module 11: Programming in C++
Objectives & Classes and Objects
Outline
Classes
Objects
Data Members
Partha Pratim Das
Complex
Rectangle
Stack
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur
Member
Functions
[email protected]
Complex
Rectangle
Stack
Module 11
Objectives &
Outline
Classes
Objects
Data Members
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Module 11
Data Members
this Pointer
Complex
Rectangle State of an Object
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Data Members
Thus, classes offer data abstraction / encapsulation of
Complex Object Oriented Programming
Rectangle
Stack
Classes are similar to structures that aggregate data logically
Member
Functions A class is defined by class keyword
Complex
Rectangle
Stack Classes provide access specifiers for members to enforce data
this pointer hiding that separates implementation from interface
State of an private - accessible inside the definition of the class
Object
Complex public - accessible everywhere
Rectangle
Stack A class is a blue print for its instances (objects)
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Objects
Objects
Thus, classes offer data abstraction / encapsulation of
Object Oriented Programming
Data Members
Complex
Rectangle Classes are similar to structures that aggregate data logically
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
this pointer // Call global fn. with ’c’ as param // Invoke method print of ’c’
print(c); c.print();
State of an
Object return 0; return 0;
Complex } }
Rectangle ----- -----
Stack |4.200000+j5.300000| = 6.762396 |4.2+j5.3| = 6.7624
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Program 11.09/10: Rectangles:
Methods
Module 11 Using struct Using class
Objects
Data Members
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Objectives & Type of this pointer for a class X object: X * const this;
Outline
this pointer is accessible only in methods
Classes
#include <iostream> using namespace std;
Objects
Objectives &
Outline X a; a.f(2, 3); X::f(&a, 2, 3); // &a = this
Classes
Objects
Use of this pointer
Data Members Distinguish member from non-member
Complex class X { public: int m1, m2;
Rectangle void f(int k1, int k2) {
Stack m1 = k1; // this->m1 (member) is valid; this->k1 is invalid
this->m2 = k2; // m2 (member) is valid; this->k2 is invalid
Member
}
Functions
};
Complex
Rectangle Explicit Use
Stack // Link the object
this pointer class DoublyLinkedNode { public: DoublyLinkedNode *prev, *next; int data;
void append(DoublyLinkedNode *x) { next = x; x->prev = this; }
State of an }
Object ---
Complex // Return the object
Rectangle Complex& inc() { ++re; ++im; return *this; }
Stack
Module 11
The state of an object is determined by the combined value of
all its data members. Consider class Complex:
Partha Pratim
Das class Complex { public:
double re_, im_; // ordered tuple of data members decide the state at any time
Objectives &
double get_re { return re_; }
Outline
void set_re(double re) { re_ = re; }
Classes double get_im { return im_; }
void set_im(double im) { im_ = im; }
Objects }
State of an c.get_re();
Object // STATE 2 of c = {6.4, 5.3} // No change of state
Complex
Rectangle c.set_im(7.8);
Stack // STATE 3 of c = {6.4, 7.8}
Module 11
Consider class Point and class Rect:
Partha Pratim Data members of Rect class: Point TL; Point BR; // Point class type object
Das Data members of Point class: int x; int y
this pointer
State of an
Object
Complex
Rectangle
Stack
Module 11
Consider class Stack:
Partha Pratim Data members of Stack class: char data[5] and int top;
Das
Stack s;
// STATE 1 of s = {{?, ?, ?, ?, ?}, ?} // No data member is initialized
Objectives &
Outline s.top_ = -1;
// STATE 2 of s = {{?, ?, ?, ?, ?}, -1}
Classes
s.push(’b’);
Objects
// STATE 3 of s = {{’b’, ?, ?, ?, ?}, 0}
Data Members
s.push(’a’);
Complex
Rectangle
// STATE 4 of s = {{’b’, ’a’, ?, ?, ?}, 1}
Stack
s.empty();
Member // STATE 4 of s = {{’b’, ’a’, ?, ?, ?}, 1} // No change of state
Functions
Complex s.push(’t’);
Rectangle // STATE 5 of s = {{’b’, ’a’, ’t’, ?, ?}, 2}
Stack
s.top();
this pointer // STATE 5 of s = {{’b’, ’a’, ’t’, ?, ?}, 2} // No change of state
State of an
s.pop();
Object
// STATE 6 of s = {{’b’, ’a’, ’t’, ?, ?}, 1}
Complex
Rectangle
Stack
Module 11
Partha Pratim
We have covered the following:
Das
Module 11
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Classes
Srijoni Majumdar, TA [email protected] 9674474267
Himadri B G S Bhuyan, TA [email protected] 9438911655
Objects
Data Members
Complex
Rectangle
Stack
Member
Functions
Complex
Rectangle
Stack
this pointer
State of an
Object
Complex
Rectangle
Stack
Partha Pratim
Das Module 12: Programming in C++
Objectives & Access Specifiers
Outline
Access
Specifiers
public and
private Partha Pratim Das
Information
Hiding
Stack (public)
Department of Computer Science and Engineering
Stack (private) Indian Institute of Technology, Kharagpur
Get-Set Idiom
[email protected]
Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 12
Information
Hiding
Stack (public)
Stack (private)
Get-Set Idiom
Summary
Module 12
Get-Set Idiom
Summary
Get-Set Idiom
The keywords public and private are the Access Specifiers
Summary Unless specified, the access of the members of a class is
considered private
A class may have multiple access specifier. The effect of one
continues till the next is encountered
Module 12
Information
using the class
Hiding
Stack (public)
Customarily, we put all attributes in private part and the
Stack (private) methods in public part. This ensures:
Get-Set Idiom The state of an object can be changed only through one
Summary of its methods (with the knowledge of the class)
The behavior of an object is accessible to others through
the methods
This is known as Information Hiding
Module 12
Get-Set Idiom
stack
Summary
• public data reveals the internals of the stack (no information hiding)
• Spills data structure codes (Exposed Init / De-Init) into the application (main)
• To switch from array to vector or vice-versa the application needs to change
• Application may intentionally or inadvertently tamper the value of top – this corrupts the stack!
• s.top = 2; destroys consistency of the stack and causes wrong output
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Program 12.05/06: Stack:
Implementations using private data – Safe
Module 12 Using dynamic array Using vector
Application
#include "Stack.h"
int main() {
Stack s; char str[10] = "ABCDE";
for (int i = 0; i < 5; ++i) s.push(str[i]);
while (!s.empty()) { cout << s.top(); s.pop(); }
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Get–Set Methods:
Idiom for fine-grained Access Control
Module 12 As noted, we put all attributes in private and the methods in
Partha Pratim public. This restricts the access to data completely
Das
To fine-grain the access to data we provide selective public
Objectives & member functions to read (get) and / or write (set) data
Outline
class MyClass { // private
Access int readWrite_; // Like re_, im_ in Complex -- common aggregated members
Specifiers
public and int readOnly_; // Like DateOfBirth, Emp_ID, RollNo -- should not need a change
private
Module 12
Get-Set Idiom
Summary
Module 12
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Access
Srijoni Majumdar, TA [email protected] 9674474267
Specifiers Himadri B G S Bhuyan, TA [email protected] 9438911655
public and
private
Information
Hiding
Stack (public)
Stack (private)
Get-Set Idiom
Summary
Partha Pratim
Das Module 13: Programming in C++
Objectives & Constructors, Destructors & Object Lifetime
Outline
Constructor
Parameterized
Overloaded
Destructor
Partha Pratim Das
Default
Constructor Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur
Object
Lifetime
[email protected]
Automatic
Static
Dynamic
Module 13
Destructor
Default
Constructor
Object
Lifetime
Automatic
Static
Dynamic
Summary
Module 13
Constructor
Destructor
Parameterized
Overloaded Default Constructor
Destructor Object Lifetime
Default Automatic
Constructor
Object
Array
Lifetime Dynamic
Automatic
Static
Dynamic
Summary
• Spills data structure codes into application • No code in application, but init() to be called
• public data reveals the internals • private data protects the internals
• To switch container, application needs to change • Switching container is seamless
• Application may corrupt the stack! • Application cannot corrupt the stack
Object c1.print();
Lifetime c2.print();
Automatic c3.print();
Static
Dynamic return 0;
}
Summary
-----
|4.2+j5.3| = 6.7624
|4.2+j0| = 4.2
|0+j0| = 0
Module 13
Constructor
Partha Pratim
Das A constructor with no parameter is called a Default
Constructor
Objectives &
Outline If no constructor is provided by the user, the compiler
Constructor supplies a free default constructor
Parameterized
Overloaded
Compiler-provided (default) constructor, understandably,
Destructor
cannot initialize the object to proper values. It has no code
Default
in its body
Constructor Default constructors (free or user-provided) are required to
Object define arrays of objects
Lifetime
Automatic Destructor
Static
Dynamic If no destructor is provided by the user, the compiler
Summary supplies a free default destructor
Compiler-provided (default) destructor has no code in its
body
Destructor
Complex::~Complex() // Dtor
Default {
return; // E7: Dtor called cout << "Dtor:" << endl;
Constructor
} // E9: De-Allocation of c from Stack } // E8: Object Lifetime ENDS
Object
Lifetime Event Sequence and Object Lifetime
Automatic
Static E1 MyFunc called. Stackframe allocated. c is a part of Stackframe
Dynamic E2 Control to pass Complex c. Ctor Complex::Complex(&c) called with the address of c on the frame
E3 Control on Initializer list of Complex::Complex(). Data members initialized (constructed)
Summary
E4 Object Lifetime STARTS for c. Control reaches the start of the body of Ctor. Ctor executes
E5 Control at c.norm(). Complex::norm(&c) called. Object is being used
E6 Complex::norm() executes
E7 Control to pass return. Dtor Complex::~Complex(&c) called
E8 Dtor executes. Control reaches the end of the body of Dtor. Object Lifetime ENDS for c
E9 return executes. Stackframe including c de-allocated. Control returns to caller
Default
Compiler provides free Default Constructor and
Constructor Destructor, if not provides by the program
Object
Lifetime Objects have a well-defined lifetime spanning from
Automatic
Static execution of the beginning of the body of a constructor to
Dynamic
the execution till the end of the body of the destructor
Summary
Memory for an object must be available before its
construction and can be released only after its destruction
Module 13
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Constructor
Srijoni Majumdar, TA [email protected] 9674474267
Parameterized Himadri B G S Bhuyan, TA [email protected] 9438911655
Overloaded
Destructor
Default
Constructor
Object
Lifetime
Automatic
Static
Dynamic
Summary
Partha Pratim
Das Module 14: Programming in C++
Objectives & Copy Constructor and Copy Assignment Operator
Outline
Lifetime
Examples
String
Date Partha Pratim Das
Rect
Name & Address
CreditCard Department of Computer Science and Engineering
Copy Indian Institute of Technology, Kharagpur
Constructor
Call by value [email protected]
Signature
Data members
Free Copy
Constructor
Tanwi Mallick
Copy Srijoni Majumdar
Assignment
Operator
Himadri B G S Bhuyan
Copy Pointer
Self-Copy
Signature
Module 14
Copy
Constructor
Call by value
Signature
Data members
Free Copy
Constructor
Copy
Assignment
Operator
Copy Pointer
Self-Copy
Signature
Module 14
Copy
Input Parameters
Constructor Return Type
Call by value
Signature Copy with Pointers – Shallow and Deep Copy
Data members
Free Copy
Self-copy
Constructor
Copy
Assignment
Operator
Copy Pointer
Self-Copy
Signature
Partha Pratim int init_m1(int m) { // Func. to init m1_ int init_m1(int m) { // Func. to init m1_
Das cout << "Init m1_: " << m << endl; cout << "Init m1_: " << m << endl;
return m; return m;
} }
Objectives &
int init_m2(int m) { // Func. to init m2_ int init_m2(int m) { // Func. to init m2_
Outline
cout << "Init m2_: " << m << endl; cout << "Init m2_: " << m << endl;
Lifetime return m; return m;
Examples } }
class X { class X {
String
int m1_; // Initialize 1st int m2_; // Order of data members swapped
Date
Rect
int m2_; // Initialize 2nd int m1_;
Name & Address
public: public:
CreditCard X(int m1, int m2) : X(int m1, int m2) :
m1_(init_m1(m1)), // Called 1st m1_(init_m1(m1)), // Called 2nd
Copy m2_(init_m2(m2)) // Called 2nd m2_(init_m2(m2)) // Called 1st
Constructor { cout << "Ctor: " << endl; } { cout << "Ctor: " << endl; }
Call by value ~X() { cout << "Dtor: " << endl; } ~X() { cout << "Dtor: " << endl; }
Signature }; };
Data members int main() { X a(2, 3); return 0; } int main() { X a(2, 3); return 0; }
Free Copy ----- -----
Constructor Init m1_: 2 Init m2_: 3
Copy Init m2_: 3 Init m1_: 2
Assignment Ctor: Ctor:
Operator Dtor: Dtor:
Copy Pointer • Order of initialization does not depend on the order in the initialization list. It depends on
Self-Copy
the order of data members in the definition
Signature
Copy
Constructor
Call by value • len precedes str in list of data
Signature members
Data members • len (strlen(str )) is executed
Free Copy before str (strdup(s))
Constructor
• When strlen(str ) is called str
Copy is still uninitialized
Assignment • Causes the program to crash as
Operator shown in the message box
Copy Pointer
Self-Copy
Signature
Partha Pratim char monthNames[][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
Das "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
char dayNames[][10] = { "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
Objectives &
class Date {
Outline
enum Month { Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
Lifetime enum Day { Mon, Tue, Wed, Thr, Fri, Sat, Sun };
Examples typedef unsigned int UINT;
UINT date_; Month month_; UINT year_;
String
public:
Date
Rect
Date(UINT d, UINT m, UINT y) : date_(d), month_((Month)m), year_(y)
Name & Address
{ cout << "ctor: "; print(); }
CreditCard ~Date() { cout << "dtor: "; print(); }
void print() { cout << date_ << "/" << monthNames[month_ - 1] << "/" << year_ << endl; }
Copy bool validDate() { /* Check validity */ return true; } // Not implemented
Constructor Day day() { /* Compute day from date using time.h */ return Mon; } // Not implemented
Call by value };
Signature int main() {
Data members Date d(30, 7, 1961);
Free Copy d.print();
Constructor return 0;
Copy }
Assignment -----
Operator ctor: 30/Jul/1961
Copy Pointer
30/Jul/1961
Self-Copy
dtor: 30/Jul/1961
Signature
Module 14
Partha Pratim
We know:
Das Complex c1 = {4.2, 5.9}; // or c1(4.2, 5.9)
Objectives &
invokes
Outline Constructor Complex::Complex(double, double);
Lifetime
Examples
String
Date
Which constructor is invoked for?
Rect Complex c2(c1);
Name & Address
CreditCard
Copy
Constructor Or for?
Call by value
Signature
Complex c2 = c1;
Data members
Free Copy
Constructor
Copy
It is the Copy Constructor that take an object of the
Assignment same type and constructs a copy:
Operator
Copy Pointer Complex::Complex(const Complex &);
Self-Copy
Signature
Copy
Call-by-value: Make a copy (clone) of the actual parameter
Constructor as a formal parameter. This needs a Copy Constructor
Call by value
Signature
Data members
Free Copy
Return-by-value: Make a copy (clone) of the computed
Constructor
value as a return value. This needs a Copy Constructor
Copy
Assignment
Operator
Copy Constructor is needed for initializing the data
Copy Pointer members of a UDT from an existing value
Self-Copy
Signature
Module 14
If no copy constructor is provided by the user, the compiler
Partha Pratim
Das supplies a free copy constructor
Objectives & Compiler-provided copy constructor, understandably,
Outline
cannot initialize the object to proper values. It has no
Lifetime
Examples code in its body. It performs a bit-copy
String
Date
Rect
Name & Address
CreditCard
Copy
Constructor
Call by value
Signature
Data members
Free Copy
Constructor
Copy
Assignment
Operator
Copy Pointer
Self-Copy
Signature
Copy return 0;
Constructor }
Call by value User-defined CCtor Free CCtor
Signature (Partha: 6) (Partha: 6)
Data members strToUpper: (PARTHA: 6) strToUpper: (PARTHA: 6)
Free Copy (Partha: 6) (?????????????????????????????: 6)
Constructor
• User has provided no copy constructor. Compiler provides free copy constructor
Copy • Free copy constructor performs bit-copy - hence no allocation is done for str when actual parameter s
Assignment is copied to formal parameter a. s.str is merely copied to a.str and both continue to point to the same
Operator memory. On exit from strToUpper, a is destructed and a.str is deallocated. Hence in main access to
Copy Pointer s.str is corrupted. Program crashes
Self-Copy • Shallow Copy: With bit-copy, only the pointer is copied - not the pointed object. This may be risky
Signature
Module 14
Module 14
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Lifetime
Srijoni Majumdar, TA [email protected] 9674474267
Examples Himadri B G S Bhuyan, TA [email protected] 9438911655
String
Date
Rect
Name & Address
CreditCard
Copy
Constructor
Call by value
Signature
Data members
Free Copy
Constructor
Copy
Assignment
Operator
Copy Pointer
Self-Copy
Signature
Partha Pratim
Das
Module 15: Programming in C++
Objectives &
Outline
Const-ness
Constant
Objects
Constant Data
Department of Computer Science and Engineering
Members Indian Institute of Technology, Kharagpur
Credit Card
Example [email protected]
mutable
Members
Module 15
Constant
Objects
Constant
Member
Functions
Constant Data
Members
Credit Card
Example
mutable
Members
Summary
Module 15
Constant Data
Members
Credit Card
Example
mutable
Members
Summary
Like objects of built-in type, objects of user-defined types can also be made
Module 15
constant
Partha Pratim
Das
If an object is constant, none of its data members can be changed
The type of the this pointer of a constant object of class, say, MyClass is:
Objectives &
Outline
// Const Pointer to Const Object
Constant const MyClass * const this;
Objects
Constant
Member instead of
Functions
Constant Data
Members
void setMember(int i) const
Credit Card { myMember_ = i; } // data member cannot be changed
Example
mutable
Members
gives an error
Summary
Interesting, non-constant objects can invoke constant member functions (by
casting – we discuss later) and, of course, non-constant member functions
Constant objects, however, can only invoke constant member functions
All member functions that do not need to change an object must be
declared as constant member functions
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Program 15.03: Example:
Constant Member Functions
#include <iostream>
Module 15 using namespace std;
• Now myConstObj can invoke getMember() and print(), but cannot invoke setMember()
• Naturally myConstObj cannot update myPubMember
• myObj can invoke all of getMember(), print(), and setMember()
NPTEL MOOCs Programming in C++ Partha Pratim Das 8
Constant Data members
Often we need part of an object, that is, one or more data members to be
Module 15
constant (non-changeable after construction) while the rest of the data
Partha Pratim members should be changeable. For example:
Das
For an Employee: employee ID and DoB should be non-changeable
Objectives & while designation, address, salary etc. should be changeable
Outline For a Student: roll number and DoB should be non-changeable while
Constant year of study, address, gpa etc. should be changeable
Objects For a Credit Card: card number and name of holder should be
Constant non-changeable while date of issue, date of expiry, address, cvv
Member number gpa etc. should be changeable
Functions
Do this by making the non-changeable data members as constant
Constant Data
Members To make a data member constant, we need to put the const keyword
Credit Card before the declaration of the member in the class
Example
Module 15
We now illustrate constant data members with a complete
Partha Pratim
Das example of CreditCard class with the following supporting
Objectives &
classes:
Outline
String class
Constant
Objects Date class
Constant
Member Name class
Functions
Constant Data
Address class
Members
Credit Card
Example
mutable
Members
Summary
5321711934640027 David Cameron 10 Downing Street London SW1A 2AA 1/Jul/2017 1/Jun/2019 127
• We prefix Name holder with const. Now the holder name cannot be changed after construction
• In setHolder(), we get a compilation error for holder = h; in an attempt to change holder
• With const prefix Name holder becomes constant – unchangeable
5321711934640027 Sharlock Holmes 10 Downing Street London SW1A 2AA 1/Jul/2017 1/Jun/2019 127
Module 15
While a constant data member is not changeable even in a non-constant
Partha Pratim object, a mutable data member is changeable in a constant object
Das
mutable is provided to model Logical (Semantic) const-ness against the
Objectives &
default Bit-wise (Syntactic) const-ness of C++
Outline
Note that:
Constant
Objects
mutable is applicable only to data members and not to variables
Reference data members cannot be declared mutable
Constant Static data members cannot be declared mutable
Member
Functions const data members cannot be declared mutable
Constant Data If a data member is declared mutable, then it is legal to assign a value to it
Members from a const member function
Credit Card
Example Let us see an example
mutable
Members
Summary
• Here a MathObject is logically constant; but we use mutable members for computation
• Employee is not logically constant. If it is, then salary should also be const
• Design on right makes that explicit
Module 15
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Constant
Srijoni Majumdar, TA [email protected] 9674474267
Objects Himadri B G S Bhuyan, TA [email protected] 9438911655
Constant
Member
Functions
Constant Data
Members
Credit Card
Example
mutable
Members
Summary
Partha Pratim
Das
Module 16: Programming in C++
Objectives &
Outline
static Members
static data
member
Print Task
Partha Pratim Das
static
Member
function Department of Computer Science and Engineering
Print Task
Indian Institute of Technology, Kharagpur
Singleton
Class [email protected]
Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 16
Objectives &
Outline
static data
member
Print Task
static
Member
function
Print Task
Singleton
Class
Summary
Module 16
Singleton
Class
Summary
Module 16
A static member function
Partha Pratim does not have this pointer – not associated with any object
Das
cannot access non-static data members
Objectives & cannot invoke non-static member functions
Outline
can be accessed
static data
member with the class-name followed by the scope resolution operator (::)
Print Task
as a member of any object of the class
static
Member
function is needed to read / write static data members
Print Task Again, for encapsulation static data members should be private
Singleton get()-set() idiom is built for access (static member functions in
Class
public)
Summary
may initialize static data members even before any object creation
cannot co-exist with a non-static version of the same function
cannot be declared as const
Module 16
Partha Pratim A class is called a Singleton if it can have only one instance
Das
Many classes are singleton:
Objectives &
Outline
President of India
static data
Prime Minister of India
member Director of IIT Kharagpur
Print Task
...
static
Member
function
How to implement a Singleton Class?
Print Task
How to restrict that user can created only one instance?
Singleton
Class
Summary
In the recorded video the destructor was directly called by Printer::printer().˜Printer(); This is wrong and
will leak memory. It is corrected here with delete &Printer::printer();
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Program 16.05: Using function-local static Data
Singleton Printer
#include <iostream>
Module 16 using namespace std;
Module 16
static
Member
function
Print Task
Singleton
Class
Summary
Module 16
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
static data
Srijoni Majumdar, TA [email protected] 9674474267
member Himadri B G S Bhuyan, TA [email protected] 9438911655
Print Task
static
Member
function
Print Task
Singleton
Class
Summary
Partha Pratim
Das
Module 17: Programming in C++
Objectives &
Outline
friend Function and friend Class
friend
function
Matrix-Vector
Multiplication Partha Pratim Das
Linked List
friend class
Linked List
Department of Computer Science and Engineering
Iterator Indian Institute of Technology, Kharagpur
Notes
[email protected]
Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 17
Objectives &
Outline
friend
function
Matrix-Vector
Multiplication
Linked List
friend class
Linked List
Iterator
Notes
Summary
Module 17
Notes
Summary
In the recorded video void display(const MyClass& a); is included in the class MyClass on left by mistake.
This should be ignored. It is corrected here.
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
friend function
Module 17
Notes
Summary
• List is built on Node. Hence List needs to know the internals of Node
• void List::append(Node *); needs the internals of Node – hence friend member function is used
• void List::display(); needs the internals of Node – hence friend member function is used
• We can do better with friend classes
NPTEL MOOCs Programming in C++ Partha Pratim Das 8
friend class
Module 17
Notes
Summary
• List class is now a friend of Node class. Hence it has full visibility into the internals of Node
• When multiple member functions need to be friends, it is better to use friend class
Module 17
Notes
Summary
Module 17
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
friend
Srijoni Majumdar, TA [email protected] 9674474267
function Himadri B G S Bhuyan, TA [email protected] 9438911655
Matrix-Vector
Multiplication
Linked List
friend class
Linked List
Iterator
Notes
Summary
Partha Pratim
Das Module 18: Programming in C++
Objectives & Overloading Operator for User-Defined Types: Part 1
Outline
Motivation
Operator
Function Partha Pratim Das
Using global
function
public data
Department of Computer Science and Engineering
members Indian Institute of Technology, Kharagpur
private data
members
[email protected]
Using member
function
operator+
operator= Tanwi Mallick
Unary Operators Srijoni Majumdar
Summary Himadri B G S Bhuyan
Module 18
Using global
function
public data
members
private data
members
Using member
function
operator+
operator=
Unary Operators
Summary
Module 18
Using global
Using Member function
function operator+
public data
members operator=
private data
members Unary operators
Using member
function
operator+
operator=
Unary Operators
Summary
Objectives & The left operand is the invoking object – right is taken as a parameter
Outline
Unary Operator:
Motivation
MyType operator-(); // Operator function for Unary minus
Operator
Function
MyType operator++(); // For Pre-Incrementer
MyType operator++(int); // For post-Incrementer
Using global
function
public data The only operand is the invoking object
members
private data Note: The parameters may not be constant and may be passed by value.
members
The return may also be by reference and may be constant
Using member
function Examples:
operator+ Operator Expression Operator Function
operator=
Unary Operators a + b a.operator+(b)
Summary a = b a.operator=(b)
++a a.operator++()
a++ a.operator++(int) // Special Case
c = a + b c.operator =(a.operator+(b))
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Operator Overloading – Summary of Rules:
RECAP (Module 9)
Module 18 No new operator such as **, <>, or &| can be defined for overloading
Summary • Output: Real: 31, Imaginary: 42.5 • Output: First Name: Partha, Last Name: Das,
Full name: Partha Das
• operator+ is overloaded to perform addition of • operator+ is overloaded to perform concat of
two complex numbers which are of struct complx first name and last to form full name. The data
type type is struct String
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Program 18.02: Using Global Function – Safe
(private Data members)
#include <iostream> Complex operator+(Complex &t1, Complex &t2) {
Module 18
using namespace std; Complex sum;
class Complex { // Private data members sum.set_real(t1.real() + t2.real());
Partha Pratim double re, im; sum.set_img(t1.img() + t2.img());
Das public: return sum;
Complex(double a=0.0, double b=0.0): }
Objectives & re(a), im(b) {} int main() {
Outline ~Complex() {} Complex c1(4.5, 25.25), c2(8.3, 10.25), c3;
void display(); cout << "1st complex No:";
Motivation double real() { return re;} c1.display(); •
double img() { return im;} cout << "2nd complex No:";
Operator double set_real(double r) { re = r; } c2.display();
Function double set_img(double i) { im = i; } c3 = c1 + c2;
} ; cout << "Sum = ";
Using global void Complex::display() { c3.display();
function cout << re; return 0;
public data cout << " +j " << im << endl; }
members
private data
}
members
Output:
Using member
function 1st complex No: 4.5 +j 25.25
operator+ 2nd complex No: 8.3 +j 10.25
operator= Sum = 12.8 +j 35.5
Unary Operators
Summary
If there is a need to define a copy constructor then
operator= must be overloaded and vice-versa
return 0;
}
Module 18
Using member
function
operator+
operator=
Unary Operators
Summary
Module 18
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Motivation
Srijoni Majumdar, TA [email protected] 9674474267
Himadri B G S Bhuyan, TA [email protected] 9438911655
Operator
Function
Using global
function
public data
members
private data
members
Using member
function
operator+
operator=
Unary Operators
Summary
Partha Pratim
Das Module 19: Programming in C++
Objectives & Overloading Operator for User-Defined Types: Part 2
Outline
Issues in
Operator
Overloading
Partha Pratim Das
Extending
operator+
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 19
Extending
operator+
Overloading
IO Operators
Guidelines
Summary
Module 19
Extending
operator+
Overloading
IO Operators
Guidelines
Summary
Overloading
IO Operators
Complex d1(2.5, 3.2), d2(1.6, 3.3), d3;
• Note: A simpler solution uses Overload 1 and implicit casting (for this we need to remove explicit
before constructor). But that too breaks encapsulation. We discuss this when we take up cast operators
Guidelines //d3 = 4.2 + d2; // Overload 3 is not possible - needs an object of left
//d3.disp();
Summary return 0;
}
• Note: A simpler solution uses only Overload 1 and implicit casting (for this we need to remove explicit
before constructor) will be discussed when we take up cast operators
Objectives &
Outline
Complex d1, d2;
Issues in cout << d1 << d2; // (cout << d1) << d2;
Operator
Overloading
return 0;
}
Extending
operator+
ostream& Complex::operator<< (ostream& os);
Overloading
IO Operators In this case, the invocation of streaming will change to:
Guidelines
d << cout; // Left operand is the invoking object
Summary
Module 19
Module 19
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Issues in
Srijoni Majumdar, TA [email protected] 9674474267
Operator Himadri B G S Bhuyan, TA [email protected] 9438911655
Overloading
Extending
operator+
Overloading
IO Operators
Guidelines
Summary
Partha Pratim
Das Module 20: Programming in C++
Objectives & Namespace
Outline
namespace
Fundamental
namespace
Features Department of Computer Science and Engineering
Nested Indian Institute of Technology, Kharagpur
namespace
using namespace
Global
[email protected]
namespace
std namespace
namespaces are
Open Tanwi Mallick
namespace Srijoni Majumdar
vis-a-vis class Himadri B G S Bhuyan
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 1
Module Objectives
Module 20
namespace
Fundamental
namespace
Scenarios
namespace
Features
Nested
namespace
using namespace
Global
namespace
std namespace
namespaces are
Open
namespace
vis-a-vis class
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 2
Module Outline
Module 20
namespace
vis-a-vis class
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 3
namespace Fundamental
namespace
vis-a-vis class
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Program 20.01: namespace Fundamental
Example:
Module 20
#include <iostream>
Partha Pratim using namespace std;
Das
namespace MyNameSpace {
int myData; // Variable in namespace
Objectives &
void myFunction() { cout << "MyNameSpace myFunction" << endl; } // Function in namespace
Outline
class MyClass { int data; // Class in namespace
namespace public:
Fundamental MyClass(int d) : data(d) { }
void display() { cout << "MyClass data = " << data << endl; }
namespace };
Scenarios }
int main() {
namespace MyNameSpace::myData = 10; // Variable name qualified by namespace name
Features cout << "MyNameSpace::myData = " << MyNameSpace::myData << endl;
Nested
namespace MyNameSpace::myFunction(); // Function name qualified by namespace name
using namespace
Global MyNameSpace::MyClass obj(25); // Class name qualified by namespace name
namespace
std namespace obj.display();
namespaces are
Open return 0;
}
namespace
vis-a-vis class • A name in a namespace is prefixed by the name of it
Lexical Scope • Beyond scope resolution, all namespace items are treated as global
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 5
Scenario 1: Redefining a Library Function
(Program 20.02)
cstdlib has a function int abs(int n); that returns the absolute value of parameter n
Module 20 You need a special int abs(int n); function that returns the absolute value of parameter n if n is
between -128 and 127. Otherwise, it returns 0
Partha Pratim Once you add your abs, you cannot use the abs from library! It is hidden and gone!
Das namespace comes to your rescue
Name-hiding: abs() namespace: abs()
Objectives & #include <iostream> #include <iostream>
Outline #include <cstdlib> #include <cstdlib>
namespace
namespace myNS {
Fundamental
int abs(int n) { int abs(int n) {
namespace if (n < -128) return 0; if (n < -128) return 0;
Scenarios if (n > 127) return 0; if (n > 127) return 0;
if (n < 0) return -n; if (n < 0) return -n;
namespace return n; return n;
Features } }
Nested }
namespace int main() { int main() {
using namespace std::cout << abs(-203) << " " std::cout << myNS::abs(-203) << " "
Global << abs(-6) << " " << myNS::abs(-6) << " "
namespace
<< abs(77) << " " << myNS::abs(77) << " "
std namespace
<< abs(179) << std::endl; << myNS::abs(179) << std::endl;
namespaces are
Open // Output: 0 6 77 0 // Output: 0 6 77 0
return 0; std::cout << abs(-203) << " "
namespace } << abs(-6) << " "
vis-a-vis class << abs(77) << " "
<< abs(179) << std::endl;
Lexical Scope // Output: 203 6 77 179
return 0;
Summary
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Scenario 2: Students’ Record Application:
The Setting (Program 20.03)
An organization is developing an application to process students records
Module 20
class St for Students and class StReg for list of Students are:
Partha Pratim #include <iostream>
Das using namespace std;
class St { public: // A Student
Objectives & typedef enum GENDER { male = 0, female };
Outline St(char *n, GENDER g) : name(strcpy(new char[strlen(n) + 1], n)), gender(g) {}
void setRoll(int r) { roll = r; } // Set roll while adding the student
namespace GENDER getGender() { return gender; } // Get the gender for processing
Fundamental friend ostream& operator<< (ostream& os, const St& s) { // Print a record
cout << ((s.gender == St::male) ? "Male " : "Female ")
namespace << s.name << " " << s.roll << endl;
Scenarios return os;
}
namespace private:
Features char *name; GENDER gender; // name and gender provided for the student
Nested int roll; // roll is assigned by the system
namespace
};
using namespace
Global
class StReg { // Students’ Register
namespace St **rec; // List of students
std namespace int nStudents; // Number of student
namespaces are public:
Open StReg(int size) : rec(new St*[size]), nStudents(0) {}
namespace void add(Students* s) { rec[nStudents] = s; s->setRoll(++nStudents); }
vis-a-vis class Students *getStudent(int r) { return (r == nStudents + 1) ? 0 : rec[r - 1]; }
};
Lexical Scope
The classes are included in a header file Students.h
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Scenario 2: Students’ Record Application:
Team at Work (Program 20.03)
Two engineers – Sabita and Niloy – are assigned to develop processing applications for male and
Module 20 female students respectively. Both are given the Students.h file
The lead Purnima of Sabita and Niloy has the responsibility to integrate what they produce and
Partha Pratim prepare a single application for both male and female students. The engineers produce:
Das
Processing for males by Sabita Processing for females by Niloy
////////////// App1.cpp ////////////// ////////////// App2.cpp //////////////
Objectives & #include <iostream> #include <iostream>
Outline using namespace std; using namespace std;
#include "Students.h" #include "Students.h"
namespace
extern StReg *reg; extern StReg *reg;
Fundamental
void ProcessStduents() { void ProcessStduents() {
namespace cout << "MALE STUDENTS: " << endl; cout << "FEMALE STUDENTS: " << endl;
Scenarios int r = 1; St *s; int r = 1; St *s;
while (s = reg->getStudent(r++)) while (s = reg->getStudent(r++))
namespace if (s->getGender() == if (s->getGender() ==
Features St::male) St::female)
Nested cout << *s; cout << *s;
namespace cout << endl << endl; cout << endl << endl;
using namespace return; return;
Global } }
namespace
////////////// Main.cpp ////////////// ////////////// Main.cpp //////////////
std namespace
#include <iostream> #include <iostream>
namespaces are
Open using namespace std; using namespace std;
#include "Students.h" #include "Students.h"
namespace StReg *reg = new StReg(1000); StReg *reg = new StReg(1000);
vis-a-vis class int main() { int main() {
St s("Partha", St::male); reg->add(&s); St s("Ramala", St::female); reg->add(&s);
Lexical Scope ProcessStduents(); ProcessStduents();
return 0; return 0;
Summary
} }
NPTEL MOOCs Programming in C++ Partha Pratim Das 8
Scenario 2: Students’ Record Application:
The Integration Nightmare (Program 20.03)
To integrate, Purnima prepares the following main() in her Main.cpp where she intends to call the
Module 20 processing functions for males (as prepared by Sabita) and for females (as prepared by Niloy) one
after the other:
Partha Pratim #include <iostream>
Das using namespace std;
#include "Students.h"
Objectives &
Outline void ProcessStduents(); // Function from App1.cpp by Sabita
void ProcessStduents(); // Function from App2.cpp by Niloy
namespace
Fundamental StReg *reg = new StReg(1000);
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Scenario 2: Students’ Record Application:
A Good Night’s Sleep (Program 20.03)
Now the integration gets smooth:
Module 20
#include <iostream>
using namespace std;
Partha Pratim
Das #include "Students.h"
namespace
vis-a-vis class
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Program 20.04: Nested namespace
namespace
vis-a-vis class return 0;
}
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Program 20.05: Using using namespace and
using for shortcut
Using using namespace we can avoid lengthy prefixes
Module 20
namespace name1 {
Objectives &
int v11 = 1;
Outline
int v12 = 2;
namespace }
Fundamental
namespace name2 {
namespace int v21 = 3;
Scenarios int v22 = 4;
}
namespace
Features using namespace name1; // All symbols of namespace name1 will be available
Nested using name2::v21; // Only v21 symbol of namespace name2 will be available
namespace
using namespace int main() {
Global cout << v11 << endl; // name1::v11
namespace
std namespace
cout << name1::v12 << endl; // name1::v12
namespaces are cout << v21 << endl; // name2::v21
Open cout << name2::v21 << endl; // name2::v21
cout << v22 << endl; // Treated as undefined
namespace
vis-a-vis class return 0;
}
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 13
Program 20.06: Global namespace
namespace cout << data << endl; // 1 // name1::data -- Hides global data
Features cout << name1::data << endl; // 1
Nested cout << ::data << endl; // 0 // ::data -- global data
namespace
using namespace return 0;
Global }
namespace
std namespace
namespaces are
Open
• Items in Global namespace may be accessed by scope resolution operator (::)
namespace
vis-a-vis class
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 14
Program 20.07: std Namespace
Module 20
• Entire C++ Standard Library is put in its own namespace, called std
Partha Pratim
Das Without using using std With using using std
namespace • It is useful if a few library is to be used; no need • When several libraries are to be used it is a
vis-a-vis class to add entire std library to the global namespace convenient method
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 15
Program 20.08: namespaces are Open
Module 20
namespace are open: New Declarations can be added
Partha Pratim
Das #include <iostream>
using namespace std;
Objectives &
Outline
namespace open
namespace { int x = 30; }
Fundamental
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 16
namespace vis-a-vis class
namespace
vis-a-vis class
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 17
Lexical Scope
namespace
vis-a-vis class
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 18
Lexical Scope
Scopes may be named or Unnamed
Module 20
Named Scope – Option to refer to the scope from outside
Partha Pratim
Das Class Scope – class name
Namespace Scope – namespace name or unnamed
Objectives & Global Scope – ”::”
Outline
Unnamed Scope
namespace
Fundamental
Expression Scope
Block Scope
namespace
Scenarios
Function Scope
File Scope
namespace
Features Scopes may or may not be nested
Nested
namespace Scopes that may be nested
using namespace
Global Block Scope
namespace
std namespace
Class Scope
namespaces are Namespace Scope
Open
namespace
Scopes that cannot be nested
vis-a-vis class Expression Scope
Lexical Scope Function Scope – may contain Class Scopes
File Scope – will contain several other scopes
Summary
Global Scope – will contain several other scopes
NPTEL MOOCs Programming in C++ Partha Pratim Das 19
Module Summary
Module 20
namespace
Features
Nested
namespace
using namespace
Global
namespace
std namespace
namespaces are
Open
namespace
vis-a-vis class
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 20
Instructor and TAs
Module 20
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
namespace
Srijoni Majumdar, TA [email protected] 9674474267
Fundamental Himadri B G S Bhuyan, TA [email protected] 9438911655
namespace
Scenarios
namespace
Features
Nested
namespace
using namespace
Global
namespace
std namespace
namespaces are
Open
namespace
vis-a-vis class
Lexical Scope
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 21
Module 21
Partha Pratim
Das Module 21: Programming in C++
Objectives &
Outline
Inheritance: Part 1 (Inheritance Semantics)
ISA
Relationship
Inheritance in
C++
Partha Pratim Das
Semantics
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 21
ISA
Relationship
Inheritance in
C++
Semantics
Summary
Module 21
Module 21
Summary
Partha Pratim
Das
class Employee; // Base Class = Employee
Objectives & class Manager: public Employee; // Derived Class = Manager
Outline
TwoWheeler ISA Vehicle; ThreeWheeler ISA Vehicle [Hybrid Inheritance]
ISA
Relationship
Inheritance in
C++
Semantics
Summary
Module 21
ISA
Relationship
Inheritance in
C++
Semantics
Summary
Module 21
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
ISA
Srijoni Majumdar, TA [email protected] 9674474267
Relationship Himadri B G S Bhuyan, TA [email protected] 9438911655
Inheritance in
C++
Semantics
Summary
Partha Pratim
Das Module 22: Programming in C++
Objectives &
Outline
Inheritance: Part 2 (Data Member & Member Function - Override)
Inheritance in
C++
Data Members
Overrides and
Overloads
Partha Pratim Das
Summary
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 22
Summary
Module 22
D d;
Object Layout
Object b Object d
data1B
data1B
data2B
data2B
infoD
B b; B b;
D d; D d;
Module 22
Summary
Module 22
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Inheritance in
Srijoni Majumdar, TA [email protected] 9674474267
C++ Himadri B G S Bhuyan, TA [email protected] 9438911655
Data Members
Overrides and
Overloads
Summary
Partha Pratim
Das Module 23: Programming in C++
Objectives &
Outline
Inheritance: Part 3 (Constructor & Destructor - Object Lifetime)
Inheritance in
C++
protected
Access
Constructor &
Partha Pratim Das
Destructor
Object Lifetime
Department of Computer Science and Engineering
Summary
Indian Institute of Technology, Kharagpur
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 23
Summary
Module 23
Summary
protected Access
Constructor & Destructor
Object Lifetime
Example – Phone Hierarchy
Inheritance in C++ (private)
Implemented-As Semantics
B b(0); B b(0);
D d(1, 2); D d(1, 2);
b.Print(); b.Print();
d.Print(); d.Print();
B b(0); B b(0);
D d(1, 2); D d(1, 2);
B Object: 0 B Object: 0
B Object: 1 D Object: 1 2
Summary
A constructor of the Derived class must first call a
constructor of the Base class to construct the Base class
instance of the Derived class
The destructor of the Derived class must call the
destructor of the Base class to destruct the Base class
instance of the Derived class
B b(5);
D d1(1, 2); // ctor-1: Explicit construction of Base
D d2(3); // ctor-2: Default construction of Base
Object Layout
1 0
5
2 3
Module 23
Summary
Module 23
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Inheritance in
Srijoni Majumdar, TA [email protected] 9674474267
C++ Himadri B G S Bhuyan, TA [email protected] 9438911655
protected
Access
Constructor &
Destructor
Object Lifetime
Summary
Partha Pratim
Das Module 24: Programming in C++
Objectives &
Outline
Inheritance: Part 4 (Example – Phone Hierarchy)
Example –
Phone
Hierarchy
Summary
Partha Pratim Das
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 24
Objectives &
Outline
Example –
Phone
Hierarchy
Summary
Module 24
Module 24
Partha Pratim
Das
Class Description
Objectives &
Outline class PhoneNumber 12-digit phone number
Example – class Name Subscriber Name (as string)
Phone
Hierarchy class Photo Image & Subscriber Name as alt text
Summary class RingTone Audio & ring tone name
class Contact PhoneNumber, Name, and Photo (op-
tional) of a contact
class AddressBook List of contacts
Summary
Add Contact void Call(PhoneNumber *p);
Number void Call(const Name& n);
Name void Answer();
void ReDial();
void SetRingTone(RingTone::RINGTONE r);
void AddContact(const char *num = 0,
const char *subs = 0);
void ReDial();
void SetRingTone(RingTone::RINGTONE r);
void AddContact(const char *num = 0,
const char *subs = 0);
Module 24
Partha Pratim
Das
Objectives &
Outline
Example –
Phone
Hierarchy MobilePhone ISA LandlinePhone
Summary LandlinePhone is generalization
MobilePhone is specialization
MobilePhone inherits the properties of LandlinePhone
SmartPhone ISA MobilePhone
MobilePhone is generalization
SmartPhone is specialization
SmartPhone inherits the properties of MobilePhone
ISA is transitive
Module 24
Partha Pratim
Das
Objectives &
Outline
Example –
Phone
Hierarchy
Summary
void Call(const PhoneNumber *p); // Override void Call(const PhoneNumber *p); // Override
void Call(const Name& n); // Overload void Call(const Name& n); // Override
//void Answer(); //void Answer();
void ReDial(); void ReDial(); // Override
void SetRingTone(RingTone::RINGTONE r); //void SetRingTone(RingTone::RINGTONE r);
void AddContact(const char *num = 0, //void AddContact(const char *num = 0,
const char *subs = 0); //const char *subs = 0);
friend ostream& operator<< (ostream& os, friend ostream& operator<< (ostream& os,
const MobilePhone& p); const SmartPhone& p);
}; };
Module 24
Partha Pratim
Das
Objectives &
Outline
Example –
Phone
Hierarchy
Summary
Module 24
Example –
Phone
Hierarchy
Summary
Module 24
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Example –
Srijoni Majumdar, TA [email protected] 9674474267
Phone Himadri B G S Bhuyan, TA [email protected] 9438911655
Hierarchy
Summary
Partha Pratim
Das Module 25: Programming in C++
Objectives &
Outline
Inheritance: Part 5 (private & protected Inheritance)
Inheritance in
C++
private
Inheritance
Partha Pratim Das
protected
Inheritance Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur
Visibility
Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 25
Inheritance in
C++
private
Inheritance
protected
Inheritance
Visibility
Use &
Examples
Summary
Module 25
protected
Name of the Base class follow the keyword
Inheritance
Visibility
Use &
Examples
Summary
Module 25 class B {
public:
Partha Pratim B() { cout << "B "; }
Das ~B() { cout << "~B "; } };
class C {
Objectives & public:
Outline C() { cout << "C "; }
~C() { cout << "~C "; } };
Inheritance in
C++
class D : public B {
private C data_;
Inheritance public:
D() { cout << "D " << endl; }
protected ~D() { cout << "~D "; }
Inheritance };
Module 25 class B {
public:
Partha Pratim B() { cout << "B "; }
Das ~B() { cout << "~B "; } };
class C {
Objectives & public:
Outline C() { cout << "C "; }
~C() { cout << "~C "; } };
Inheritance in
C++
class D : public B {
private C data_;
Inheritance public:
D() { cout << "D " << endl; }
protected ~D() { cout << "~D "; }
Inheritance };
Output:
B C D
~D ~C ~B
private
Inheritance • Private inheritance means nothing during software design, only during
protected software implementation
Inheritance
Compilers converts a derived class object (Stu- Compilers will not convert a derived class object
dent) into a base class object (Person) if the in- (Student) into a base class object (Person) if the
heritance relationship is public inheritance relationship is private
private
Inheritance • Private inheritance means something entirely different (from public inheri-
protected tance), and protected inheritance is something whose meaning eludes me to
Inheritance this day
Visibility
– Scott Meyers in Item 32, Effective C++ (3rd. Edition)
Use &
Examples
Summary
protected
Inheritance
Visibility
Use &
Examples
Summary
Module 25 class B {
protected:
Partha Pratim B() { cout << "B "; }
Das ~B() { cout << "~B "; }
};
class C : public B {
Objectives & protected:
Outline C() { cout << "C "; }
~C() { cout << "~C "; }
Inheritance in
};
C++
class D : private C {
private C data_;
Inheritance public:
D() { cout << "D " << endl; }
protected ~D() { cout << "~D "; }
Inheritance };
Module 25 class B {
protected:
Partha Pratim B() { cout << "B "; }
Das ~B() { cout << "~B "; }
};
class C : public B {
Objectives & protected:
Outline C() { cout << "C "; }
~C() { cout << "~C "; }
Inheritance in
};
C++
class D : private C {
private C data_;
Inheritance public:
D() { cout << "D " << endl; }
protected ~D() { cout << "~D "; }
Inheritance };
Output:
B C B C D
~D ~C ~B ~C ~B
c.start(); c.start();
return 0; return 0;
} }
Objectives &
Outline • Private inheritance means nothing during software
Inheritance in design, only during software implementation
C++
private
Inheritance • Private inheritance means is-implemented-in-terms of.
protected
Inheritance
It’s usually inferior to composition, but it makes sense
Visibility
when a derived class needs access to protected base class
Use &
members or needs to redefine inherited virtual functions
Examples
Summary
– Scott Meyers in Item 32, Effective C++ (3rd. Edition)
Module 25
private
Inheritance
protected
Inheritance
Visibility
Use &
Examples
Summary
Module 25
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Inheritance in Srijoni Majumdar, TA [email protected] 9674474267
C++ Himadri B G S Bhuyan, TA [email protected] 9438911655
private
Inheritance
protected
Inheritance
Visibility
Use &
Examples
Summary
Partha Pratim
Das Module 26: Programming in C++
Objectives &
Outline
Dynamic Binding (Polymorphism): Part 1
Casting
Upcast &
Downcast
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 26
Casting
Upcast &
Downcast
Static and
Dynamic
Binding
Summary
Module 26
Static and
Dynamic
Binding
Summary
Module 26
Casting is performed when a value (variable) of one type is used in place of
some other type
Partha Pratim int i = 3;
Das double d = 2.5;
Module 26
(Implicit) Casting between unrelated classes is not permitted
class A { int i; };
Partha Pratim class B { double d; };
Das
A a;
B b;
Objectives &
Outline A *p = &a;
B *q = &b;
Casting
Upcast & a = b; // error C2679: binary ’=’ : no operator found
Downcast
// which takes a right-hand operand of type ’main::B’
Static and
Dynamic a = (A)b; // error C2440: ’type cast’ : cannot convert from ’main::B’ to ’main::A’
Binding
b = a; // error C2679: binary ’=’ : no operator found
Summary // which takes a right-hand operand of type ’main::A’
b = (B)a; // error C2440: ’type cast’ : cannot convert from ’main::A’ to ’main::B’
Module 26
Forced Casting between unrelated classes is dangerous
class A { public: int i; };
Partha Pratim class B { public: double d; };
Das
A a;
B b;
Objectives &
Outline a.i = 5;
b.d = 7.2;
Casting
Upcast & A *p = &a;
Downcast
B *q = &b;
Static and
Dynamic cout << p->i << endl; // prints 5
Binding cout << q->d << endl; // prints 7.2
Summary p = (A*)&b;
q = (B*)&a;
Module 26
Casting on a hierarchy is permitted in a limited sense
class A {};
Partha Pratim class B : public A {};
Das
A *pa = 0;
B *pb = 0;
Objectives & void *pv = 0;
Outline
pa = pb; // okay ------------------------------------------------- // UPCAST
Casting
Upcast & pb = pa; // error C2440: ’=’ : cannot convert from ’A *’ to ’B *’ // DOWNCAST
Downcast
Module 26
Up-Casting is safe
class A { public: int dataA_; };
Partha Pratim class B : public A { public: int dataB_; };
Das
A a;
B b;
Objectives &
Outline a.dataA_ = 2;
b.dataA_ = 3;
Casting
b.dataB_ = 5;
Upcast &
Downcast
A *pa = &a;
Static and B *pb = &b;
Dynamic
Binding cout << pa->dataA_ << endl; // prints 2
cout << pb->dataA_ << " " << pb->dataB_ << endl; // prints 3 5
Summary
pa = &b;
#include <iostream>
Module 26
using namespace std;
Partha Pratim class B {
Das public:
void f() { cout << "B::f()" << endl; }
Objectives & virtual void g() { cout << "B::g()" << endl; }
Outline };
Module 26
Static and
Dynamic
Binding
Summary
Module 26
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Casting Srijoni Majumdar, TA [email protected] 9674474267
Upcast & Himadri B G S Bhuyan, TA [email protected] 9438911655
Downcast
Static and
Dynamic
Binding
Summary
Partha Pratim
Das Module 27: Programming in C++
Objectives &
Outline
Dynamic Binding (Polymorphism): Part 2
Binding
Types
Static Binding
Dynamic
Binding
Partha Pratim Das
Polymorphic
Type Department of Computer Science and Engineering
Summary
Indian Institute of Technology, Kharagpur
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 27
Binding
Types
Static Binding
Dynamic
Binding
Polymorphic
Type
Summary
Module 27
Polymorphic
Type
Summary
Module 27 The static type of the object is the type declared for the object
Partha Pratim while writing the code
Das
Compiler sees static type
Objectives &
Outline The dynamic type of the object is determined by the type of the
Binding object to which it currently refers
Types
Static Binding
Dynamic Compiler does not see dynamic type
Binding
Polymorphic
Type
class A {};
Summary
class B : public A {};
int main() {
A *p;
p = new B; // Static type of p = A
// Dynamic type of p = B
}
• Object d of derived class inherits the base class • If a member function of a base class is redefined
function f() and has its own function g() in a derived class with the same signature then
it masks the base class method
• Function calls are resolved at compile time • The derived class method f() is linked to the
based on static type object d. As f() is redefined in the derived class,
the base class version cannot be called with the
object of a derived class
Module 27 #include<iostream>
using namespace std;
Partha Pratim class A { public:
Das void f() {}
};
• Object b of derived class linked to with inherited base class function f() and the overloaded version
defined by the derived class f(int), based on the input parameters – function calls resolved at compile time
• p->f() always binds to B::f() • p->f() binds to B::f() for a B object, and
to D::f() for a D object
• Binding is decided by the type of pointer • Binding is decided by the type of object
• Static Binding • Dynamic Binding
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Module Summary
Module 27
Binding
Types
Static Binding
Dynamic
Binding
Polymorphic
Type
Summary
Module 27
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Binding Srijoni Majumdar, TA [email protected] 9674474267
Types Himadri B G S Bhuyan, TA [email protected] 9438911655
Static Binding
Dynamic
Binding
Polymorphic
Type
Summary
Partha Pratim
Das Module 28: Programming in C++
Objectives &
Outline
Dynamic Binding (Polymorphism): Part 3
Virtual
Destructor
Pure Virtual
Function
Partha Pratim Das
Abstract Base
Class Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur
Summary
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 28
Pure Virtual
Function
Abstract Base
Class
Summary
Module 28
Pure Virtual
Function
Abstract Base
Class
Summary
Virtual
Destructor
Pure Virtual
Function
Abstract Base
Class
Summary
Module 28
Partha Pratim
Das
Objectives &
Outline
Virtual
Destructor
Pure Virtual
Function
Abstract Base
Class
Summary
Summary
Instances for class Shapes and class ClosedConics
cannot be created
Module 28
Pure Virtual
Function
Abstract Base
Class
Summary
Module 28
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Virtual Srijoni Majumdar, TA [email protected] 9674474267
Destructor Himadri B G S Bhuyan, TA [email protected] 9438911655
Pure Virtual
Function
Abstract Base
Class
Summary
Partha Pratim
Das Module 29: Programming in C++
Objectives &
Outline
Dynamic Binding (Polymorphism): Part 4
Binding:
Exercise
Staff Salary
Processing
Partha Pratim Das
C Solution
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 29
Objectives &
Outline
Binding:
Exercise
Staff Salary
Processing
C Solution
Summary
Module 29
Summary
Initialization
Invocation pA = &a; pA = &b; pA = &c;
pA->f(2); A::f B::f B::f
pA->g(3.2); A::g A::g C::g
pA->h(&a); A::h A::h A::h
pA->h(&b); A::h A::h A::h
Initialization
Invocation pB = &a; pB = &b; pB = &c;
pB->f(2); Error B::f B::f
pB->g(3.2); Downcast A::g C::g
pB->h(&a); (A *) to No conversion (A *) to (B *)
pB->h(&b); (B *) B::h C::h
Objectives &
How to initialize objects?
Outline
Initialization functions
Binding:
Exercise
How to have a collection of mixed objects?
Staff Salary
Processing Array of union
C Solution
Objectives &
How to initialize objects?
Outline
Initialization functions
Binding:
Exercise
How to have a collection of mixed objects?
Staff Salary
Processing Array of union
C Solution
Module 29
Staff Salary
Processing
C Solution
Summary
Module 29
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Binding: Srijoni Majumdar, TA [email protected] 9674474267
Exercise Himadri B G S Bhuyan, TA [email protected] 9438911655
Staff Salary
Processing
C Solution
Summary
Partha Pratim
Das Module 30: Programming in C++
Objectives &
Outline
Dynamic Binding (Polymorphism): Part 5
Staff Salary
Processing
C Solution
C++ Solution Partha Pratim Das
Non-
Polymorphic
Hierarchy
Polymorphic Department of Computer Science and Engineering
Hierarchy
Polymorphic
Indian Institute of Technology, Kharagpur
Hierarchy
(Flexible) [email protected]
Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 30
Objectives &
Outline
Staff Salary
Processing
C Solution
C++ Solution
Non-
Polymorphic
Hierarchy
Polymorphic
Hierarchy
Polymorphic
Hierarchy
(Flexible)
Summary
Module 30
Summary
Objectives &
How to initialize objects?
Outline
Initialization functions
Staff Salary
Processing
C Solution
How to have a collection of mixed objects?
C++ Solution
Non-
Polymorphic
Array of union
Hierarchy
Polymorphic
Hierarchy
How to model variations in salary processing algorithms?
Polymorphic
Hierarchy
(Flexible) struct-specific functions
Summary
How to invoke the correct algorithm for a correct employee
type?
Function switch
Function pointers
Partha Pratim
Das
Objectives &
Outline
Staff Salary
How to represent Engineers and Managers?
Processing
Non-Polymorphic class hierarchy
C Solution
C++ Solution
Non-
How to initialize objects?
Polymorphic
Hierarchy Constructor / Destructor
Polymorphic
Hierarchy
Polymorphic How to have a collection of mixed objects?
Hierarchy
(Flexible) array of base class pointers
Summary
How to model variations in salary processing algorithms?
Member functions
How to invoke the correct algorithm for a correct employee type?
Function switch
Function pointers
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
C++ Solution: Non-Polymorphic Hierarchy
Engineer + Manager
Module 30 #include <iostream>
#include <string>
Partha Pratim using namespace std;
Das
typedef enum E_TYPE { Er, Mgr };
class Engineer { protected: string name_; E_TYPE type_;
Objectives & public: Engineer(const string& name, E_TYPE e = Er) : name_(name), type_(e) {}
Outline E_TYPE GetType() { return type_; }
void ProcessSalary() { cout << name_ << ": Process Salary for Engineer" << endl; }
Staff Salary
};
Processing
class Manager : public Engineer { Engineer *reports_[10];
C Solution public: Manager(const string& name, E_TYPE e = Mgr) : Engineer(name, e) {}
C++ Solution
void ProcessSalary() { cout << name_ << ": Process Salary for Manager" << endl; }
Non-
Polymorphic };
Hierarchy int main() { Engineer e1("Rohit"), e2("Kavita"), e3("Shambhu");
Polymorphic Manager m1("Kamala"), m2("Rajib");
Hierarchy Engineer *staff[] = { &e1, &m1, &m2, &e2, &e3 };
Polymorphic
Hierarchy
(Flexible) for (int i = 0; i < sizeof(staff) / sizeof(Engineer*); ++i) {
E_TYPE t = staff[i]->GetType();
Summary if (t == Er) staff[i]->ProcessSalary();
else if (t == Mgr) ((Manager *)staff[i])->ProcessSalary();
else cout << "Invalid Staff Type" << endl;
}
return 0;
}
Summary
Partha Pratim
Das
Summary
Partha Pratim
Das
return 0;
}
Summary
Summary
Partha Pratim
Das
Objectives &
Outline
Staff Salary
Processing
How to represent Engineers, Managers, Directors, etc.?
C Solution
C++ Solution
Polymorphic class hierarchy with an Abstract Base Employee
Non-
Polymorphic How to initialize objects?
Hierarchy
Polymorphic Constructor / Destructor
Hierarchy
Polymorphic
Hierarchy How to have a collection of mixed objects?
(Flexible)
Output:
Objectives &
Outline Rohit: Process Salary for Engineer
Kamala: Process Salary for Manager
Staff Salary
Rajib: Process Salary for Manager
Processing
Kavita: Process Salary for Engineer
C Solution Hari: Process Salary for Sales Executive
C++ Solution
Shambhu: Process Salary for Engineer
Non-
Polymorphic Ranjana: Process Salary for Director
Hierarchy Bishnu: Process Salary for Sales Executive
Polymorphic
Hierarchy
Polymorphic
Hierarchy
(Flexible)
Summary
Summary
Module 30
Staff Salary
Processing
C Solution
C++ Solution
Non-
Polymorphic
Hierarchy
Polymorphic
Hierarchy
Polymorphic
Hierarchy
(Flexible)
Summary
Module 30
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Staff Salary Srijoni Majumdar, TA [email protected] 9674474267
Processing Himadri B G S Bhuyan, TA [email protected] 9438911655
C Solution
C++ Solution
Non-
Polymorphic
Hierarchy
Polymorphic
Hierarchy
Polymorphic
Hierarchy
(Flexible)
Summary
Partha Pratim
Das
Module 31: Programming in C++
Objectives &
Outline
Virtual Function Table
Staff Salary
Processing
C Solution
C++ Solution Partha Pratim Das
Virtual
Function Department of Computer Science and Engineering
Pointer Table
Indian Institute of Technology, Kharagpur
Summary
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 31
Staff Salary
Processing
C Solution
C++ Solution
Virtual
Function
Pointer Table
Summary
Module 31
Virtual
Function
Pointer Table
Summary
Objectives &
How to initialize objects?
Outline
Initialization functions
Staff Salary
Processing
C Solution
How to have a collection of mixed objects?
C++ Solution
Virtual
Array of union
Function
Pointer Table How to model variations in salary processing algorithms?
Summary
struct-specific functions
How to invoke the correct algorithm for a correct employee
type?
Function switch
Function pointers
return 0;
}
-----
Output:
Rohit: Process Salary for Engineer
Kamala: Process Salary for Manager
Rajib: Process Salary for Manager
Kavita: Process Salary for Engineer
Shambhu: Process Salary for Engineer
Ranjana: Process Salary for Director
Partha Pratim
Das
Staff Salary
Initialization functions Ctor / Dtor
Processing
How to have a collection of How to have a collection of
C Solution
C++ Solution mixed objects? mixed objects?
Virtual array of union array of base class
Function
Pointer Table wrappers pointers
Summary How to model variations in How to model variations in
salary processing algorithms? salary processing algorithms?
functions for structs class member functions
How to invoke the correct How to invoke the correct
algorithm for a correct algorithm for a correct
employee type? employee type?
Function switch Virtual Functions
Function pointers
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
C and C++ Solutions: A Comparison
C Solution (Function Pointer) C++ Solution (Virtual Function)
Module 31 #include <stdio.h> #include <iostream>
#include <string.h> #include <string>
Partha Pratim typedef enum E_TYPE { Er, Mgr, Dir } E_TYPE; using namespace std;
Das typedef void (*psFuncPtr)(void *);
typedef struct { E_TYPE type_; void *p; } Staff;
Objectives & typedef struct { char *name_; } Engineer; class Engineer { protected: string name_;
Outline Engineer *InitEngineer(const char *name); public: Engineer(const string& name);
void ProcessSalaryEngineer(void *v); virtual void ProcessSalary(); };
Staff Salary typedef struct { char *name_; } Manager; class Manager : public Engineer {
Processing Manager *InitManager(const char *name); public: Manager(const string& name);
C Solution void ProcessSalaryManager(void *v); void ProcessSalary(); };
C++ Solution typedef struct { char *name_; } Director; class Director : public Manager {
Director *InitDirector(const char *name); public: Director(const string& name);
Virtual
void ProcessSalaryDirector(void *v); void ProcessSalary(); };
Function
int main() { psFuncPtr psArray[] = { int main() {
Pointer Table
ProcessSalaryEngineer,
Summary ProcessSalaryManager,
ProcessSalaryDirector };
Module 31
Whenever a class defines a virtual function a hidden
Partha Pratim
Das member variable is added to the class which points to an
array of pointers to (virtual) functions called the Virtual
Objectives &
Outline Function Table (VFT)
Staff Salary
Processing
VFT pointers are used at run-time to invoke the
C Solution
C++ Solution
appropriate function implementations, because at compile
Virtual time it may not yet be known if the base function is to be
Function
Pointer Table called or a derived one implemented by a class that
Summary inherits from the base class
VFT is class-specific – all instances of the class has the
same VFT
VFT carries the Run-Time Type Information (RTTI) of
objects
Module 31
Summary
Module 31
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Staff Salary Srijoni Majumdar, TA [email protected] 9674474267
Processing Himadri B G S Bhuyan, TA [email protected] 9438911655
C Solution
C++ Solution
Virtual
Function
Pointer Table
Summary
Partha Pratim
Das Module 32: Programming in C++
Objectives & Type Casting & Cast Operators: Part 1
Outline
Casting
Upcast &
Downcast
Cast
Partha Pratim Das
Operators
const cast
Department of Computer Science and Engineering
Summary Indian Institute of Technology, Kharagpur
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 32
Objectives &
Outline
Casting
Upcast &
Downcast
Cast
Operators
const cast
Summary
Module 32
Summary
To perform a type cast, the compiler
Allocates temporary storage
Initializes temporary with value being cast
double f (int i,int j) { return (double) i / j; }
// compiler generates:
double f (int i, int j) {
double temp_i = i, temp_j = j; // Conversion in temporary
return temp_i / temp_j;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Casting: C-Style:
RECAP (Module 26)
Module 32
Casting is performed when a value (variable) of one type is used in place of
some other type
Partha Pratim int i = 3;
Das double d = 2.5;
b = (B)a; // error C2440: ’type cast’ : cannot convert from ’main::A’ to ’main::B’
Summary p = (A*)&b;
q = (B*)&a;
Module 32 Casting in C
Summary
Cast
Operators
const cast
Summary
#include <iostream>
Module 32
using namespace std;
Partha Pratim class A { int i_;
Das public: A(int i) : i_(i) {}
int get() const { return i_; }
Objectives & void set(int j) { i_ = j; }
Outline };
void print(char * str) { cout << str; }
Casting
Upcast & int main() {
Downcast const char * c = "sample text";
Cast // print(c); // error: ’void print(char *)’: cannot convert argument 1
Operators // from ’const char *’ to ’char *’
const cast
print(const_cast<char *>(c));
Summary
const A a(1);
a.get();
const_cast<A&>(a).set(5);
#include <iostream>
Module 32
using namespace std;
Partha Pratim class A { int i_;
Das public: A(int i) : i_(i) {}
int get() const { return i_; }
Objectives & void set(int j) { i_ = j; }
Outline };
void print(char * str) { cout << str; }
Casting
Upcast & int main() {
Downcast const char * c = "sample text";
Cast
Operators // print(const_cast<char *>(c));
print((char *)(c)); // C-Style Cast
const cast
// const_cast<A&>(a).set(5);
((A&)a).set(5); // C-Style Cast
return 0;
}
Module 32
Cast
Operators
const cast
Summary
Module 32
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Casting Srijoni Majumdar, TA [email protected] 9674474267
Upcast & Himadri B G S Bhuyan, TA [email protected] 9438911655
Downcast
Cast
Operators
const cast
Summary
Partha Pratim
Das Module 33: Programming in C++
Objectives & Type Casting & Cast Operators: Part 2
Outline
Cast
Operators
static cast
reinterpret cast Partha Pratim Das
Summary
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur
[email protected]
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 33
Objectives &
Outline
Cast
Operators
static cast
reinterpret cast
Summary
Module 33
Module 33 Casting in C
Cast
Not only up-casts, but also down-casts
Operators No checks are performed during run-time to guarantee that the
static cast object being converted is in fact a full object of the destination type
reinterpret cast
#include <iostream>
Module 33
using namespace std;
Partha Pratim // Built-in Types
Das int main() {
int i = 2;
Objectives & double d = 3.7;
Outline double *pd = &d;
return 0;
}
#include <iostream>
Module 33
using namespace std;
Partha Pratim // Class Hierarchy
Das class A { };
class B: public A { };
Objectives &
Outline int main() {
A a;
Cast B b;
Operators
static cast // UPCAST
reinterpret cast A *p = &b; // implicit -- okay
p = static_cast<A*>(&b); // static_cast -- okay
Summary p = (A*)&b; // C-style -- okay
// DOWNCAST
q = &a; // implicit -- error
q = static_cast<B*>(&a); // static_cast -- okay: RISKY: Should use dynamic_cast
q = (B*)&a; // C-style -- okay
return 0;
}
Summary Slices the object, creates a temporary and calls the method!
class SpecialWindow: public Window { // derived class
public:
virtual void onResize() { // derived onResize impl;
Window::onResize(); // Direct call works
// B ==> A // B ==> A
a = b; // error a = b; // Uses A::A(B&)
a = static_cast<A>(b); // error a = static_cast<A>(b); // Uses A::A(B&)
a = (A)b; // error a = (A)b; // Uses A::A(B&)
return 0; return 0;
} }
// B ==> A // B ==> A
a = b; // error a = b; // B::operator A()
a = static_cast<A>(b); // error a = static_cast<A>(b); // B::operator A()
a = (A)b; // error a = (A)b; // B::operator A()
return 0; return 0;
} }
#include <iostream>
Module 33
using namespace std;
Partha Pratim class A {};
Das class B {};
A *pA;
B *pB;
return 0;
}
Module 33
Cast
Operators
static cast
reinterpret cast
Summary
Module 33
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Cast Srijoni Majumdar, TA [email protected] 9674474267
Operators Himadri B G S Bhuyan, TA [email protected] 9438911655
static cast
reinterpret cast
Summary
Partha Pratim
Das Module 34: Programming in C++
Objectives & Type Casting & Cast Operators: Part 3
Outline
Cast
Operators
dynamic cast
typeid
Partha Pratim Das
Operator
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 34
Objectives &
Outline
Cast
Operators
dynamic cast
typeid
Operator
Summary
Module 34
Module 34 Casting in C
dynamic cast can only be used with pointers and references to classes (or
Module 34
with void*)
Partha Pratim
Das
Its purpose is to ensure that the result of the type conversion points to a
valid complete object of the destination pointer type
Objectives & This naturally includes pointer upcast (converting from pointer-to-derived
Outline to pointer-to-base), in the same way as allowed as an implicit conversion
Cast But dynamic cast can also downcast (convert from pointer-to-base to
Operators
dynamic cast
pointer-to-derived) polymorphic classes (those with virtual members)
if-and-only-if the pointed object is a valid complete object of the target type
typeid
Operator If the pointed object is not a valid complete object of the target type,
Summary dynamic cast returns a null pointer
If dynamic cast is used to convert to a reference type and the conversion is
not possible, an exception of type bad cast is thrown instead
dynamic cast can also perform the other implicit casts allowed on pointers:
casting null pointers between pointers types (even between unrelated
classes), and casting any pointer of any type to a void* pointer
pA = (A*)&c; pC = dynamic_cast<C*>(pA);
cout << pA << " casts to " << pC << ": Unrelated-cast: Invalid" << endl;
pA = 0; pC = dynamic_cast<C*>(pA);
cout << pA << " casts to " << pC << ": Unrelated-cast: Valid for null" << endl;
pA = &a; pV = dynamic_cast<void*>(pA);
cout << pA << " casts to " << pV << ": Cast-to-void: Valid" << endl;
//pA = dynamic_cast<A*>(pV); // error: ’void *’: invalid expression type for dynamic_cast
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
dynamic cast Operator: References
#include <iostream>
Output:
Module 34 using namespace std;
Up-cast: Valid
Down-cast: Valid
Partha Pratim class A { public: virtual ~A() {} };
Down-cast: Invalid: Bad dynamic_cast!
Das class B: public A { };
Unrelated-cast: Invalid: Bad dynamic_cast!
class C { public: virtual ~C() {} };
Objectives &
int main() {
Outline
A a; B b; C c;
Cast try {
Operators B &rB1 = b;
A &rA2 = dynamic_cast<A&>(rB1);
dynamic cast
cout << "Up-cast: Valid" << endl;
typeid
Operator A &rA3 = b;
B &rB4 = dynamic_cast<B&>(rA3);
Summary cout << "Down-cast: Valid" << endl;
try {
A &rA5 = a;
B &rB6 = dynamic_cast<B&>(rA5);
} catch (bad_cast e) { cout << "Down-cast: Invalid: " << e.what() << endl; }
try {
A &rA7 = (A&)c;
C &rC8 = dynamic_cast<C&>(rA7);
} catch (bad_cast e) { cout << "Unrelated-cast: Invalid: " << e.what() << endl; }
} catch (bad_cast e) { cout << "Bad-cast: " << e.what() << endl; }
return 0;
}
Module 34
typeid operator is used where the dynamic type of a
Partha Pratim
Das polymorphic object must be known and for static type
identification
Objectives &
Outline typeid operator can be applied on a type or an expression
Cast
Operators typeid operator returns const std::type info. The
dynamic cast
major members are:
typeid
Operator
operator==, operator!=: checks whether the objects
Summary
refer to the same type
name: implementation-defined name of the type
typeid operator works for polymorphic type only (as it
uses RTTI – virtual function table)
If the polymorphic object is bad, the typeid throws
bad typeid exception
A &r1 = a; A &r2 = b;
cout << typeid(r1).name() << ": " << typeid(r2).name() << endl;
return 0;
}
-----
class A: class A *
class A *: class A
class B: class B *
class A *: class B
class A: class B
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Using typeid Operator: Staff Salary Application:
Polymorphic Hierarchy
#include <iostream>
Module 34
#include <string>
#include <typeinfo>
Partha Pratim using namespace std;
Das
class Engineer { protected: string name_;
Objectives & public: Engineer(const string& name) : name_(name) {}
Outline virtual void ProcessSalary() { cout << name_ << ": Process Salary for Engineer" << endl; }
};
Cast class Manager : public Engineer { Engineer *reports_[10];
Operators public: Manager(const string& name) : Engineer(name) {}
dynamic cast void ProcessSalary() { cout << name_ << ": Process Salary for Manager" << endl; }
};
typeid class Director : public Manager { Manager *reports_[10];
Operator public: Director(const string& name) : Manager(name) {}
void ProcessSalary() { cout << name_ << ": Process Salary for Director" << endl; }
Summary
};
int main() {
Engineer e("Rohit"); Manager m("Kamala"); Director d("Ranjana");
Engineer *staff[] = { &e, &m, &d };
for (int i = 0; i < sizeof(staff) / sizeof(Engineer*); ++i) {
cout << typeid(staff[i]).name() << ": " << typeid(*staff[i]).name() << endl;
}
return 0;
}
-----
class Engineer *: class Engineer
class Engineer *: class Manager
class Engineer *: class Director
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Using typeid Operator:
Non-Polymorphic Hierarchy
Module 34 #include <iostream>
#include <typeinfo>
using namespace std;
Partha Pratim
Das
// Non-Polymorphic Hierarchy
class X {};
Objectives & class Y : public X {};
Outline
int main() {
Cast X x;
Operators cout << typeid(x).name() << ": " << typeid(&x).name() << endl; // Static
dynamic cast X *q = &x;
cout << typeid(q).name() << ": " << typeid(*q).name() << endl; // Dynamic
typeid
Operator Y y;
Summary cout << typeid(y).name() << ": " << typeid(&y).name() << endl; // Static
q = &y;
cout << typeid(q).name() << ": " << typeid(*q).name() << endl; // Dynamic -- FAILS
X &r1 = x; X &r2 = y;
cout << typeid(r1).name() << ": " << typeid(r2).name() << endl;
return 0;
}
-----
class X: class X *
class X *: class X
class Y: class Y *
class X *: class X
class X: class X
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Using typeid Operator:
bad typeid Exception
#include <iostream> Output:
Module 34 #include <typeinfo> class A *
using namespace std; class A
Partha Pratim class A *
Das class A { public: virtual ~A() {} }; caught Access violation - no RTTI data!
class B : public A {}; class A *
caught Attempted a typeid of NULL pointer!
Objectives &
int main() {
Outline
A *pA = new A;
Cast try {
Operators cout << typeid(pA).name() << endl;
dynamic cast
cout << typeid(*pA).name() << endl;
} catch (const bad_typeid& e) { cout << "caught " << e.what() << endl; }
typeid
Operator delete pA;
try {
Summary cout << typeid(pA).name() << endl;
cout << typeid(*pA).name() << endl;
} catch (const bad_typeid& e) { cout << "caught " << e.what() << endl; }
pA = 0;
try {
cout << typeid(pA).name() << endl;
cout << typeid(*pA).name() << endl;
}
catch (const bad_typeid& e) { cout << "caught " << e.what() << endl; }
return 0;
}
Module 34
typeid
Operator
Summary
Module 34
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Cast Srijoni Majumdar, TA [email protected] 9674474267
Operators Himadri B G S Bhuyan, TA [email protected] 9438911655
dynamic cast
typeid
Operator
Summary
Partha Pratim
Das Module 35: Programming in C++
Objectives & Multiple Inheritance
Outline
Multiple
Inheritance in
C++
Semantics Partha Pratim Das
Data Members
Overrides and
Overloads
protected
Department of Computer Science and Engineering
Access Indian Institute of Technology, Kharagpur
Constructor &
Destructor
Object Lifetime [email protected]
Diamond
Problem
Exercise Tanwi Mallick
Design Choice Srijoni Majumdar
Himadri B G S Bhuyan
Summary
Module 35
Objectives &
Outline
Multiple
Inheritance in
C++
Semantics
Data Members
Overrides and
Overloads
protected
Access
Constructor &
Destructor
Object Lifetime
Diamond
Problem
Exercise
Design Choice
Summary
Module 35
Design Choice
Summary
Partha Pratim
Das
Objectives &
Outline
Multiple
Inheritance in
C++
Semantics
Data Members
Overrides and
Overloads
protected
Access
Constructor &
Destructor class Student; // Base Class = Student
Object Lifetime class Faculty; // Base Class = Faculty
class TA: public Student, public Faculty; // Derived Class = TA
Diamond
Problem
Exercise TA inherits properties and operations of both Student as well as Faculty
Design Choice
Summary
Objectives &
Outline
Multiple
Inheritance in
C++
class Employee; // Base Class = Employee -- Root
Semantics
class Manager: public Employee; // Derived Class = Manager
Data Members
Overrides and
class Director: public Employee; // Derived Class = Director
Overloads class ManagingDirector: public Manager, public Director;
protected // Derived Class = ManagingDirector
Access
Constructor & Manager inherits properties and operations of Employee
Destructor
Object Lifetime Director inherits properties and operations of Employee
Diamond ManagingDirector inherits properties and operations of both Manager as
Problem
Exercise
well as Director
Design Choice ManagingDirector, by transitivity, inherits properties and operations of
Employee
Summary
Multiple inheritance hierarchy usually has a common base class
This is known as the Diamond Hierarchy
NPTEL MOOCs Programming in C++ Partha Pratim Das 5
Multiple Inheritance in C++: Semantics
Objectives &
Outline
Multiple
Inheritance in
C++ class Base1; // Base Class = Base1
Semantics class Base2; // Base Class = Base2
Data Members class Derived: public Base1, public Base2;
Overrides and
Overloads // Derived Class = Derived
protected
Access Use keyword public after class name to denote inheritance
Constructor &
Destructor Name of the Base class follow the keyword
Object Lifetime
There may be more than two base classes
Diamond
Problem public and private inheritance may be mixed
Exercise
Design Choice
Summary
Design Choice A constructor of the Derived class must first call all constructors of
the Base classes to construct the Base class instances of the Derived
Summary
class – Base class constructors are called in listing order
The destructor of the Derived class must call the destructors of the
Base classes to destruct the Base class instances of the Derived class
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Multiple Inheritance in C++: Data Members and
Object Layout
Module 35 Derived ISA Base1, Base2
Partha Pratim
Das
Data Members
Derived class inherits all data members of all Base classes
Objectives &
Outline Derived class may add data members of its own
Multiple
Inheritance in Object Layout
C++
Semantics Derived class layout contains instances of each Base class
Data Members
Overrides and Further, Derived class layout will have data members of its
Overloads
protected own
Access
Constructor & C++ does not guarantee the relative position of the Base
Destructor
Object Lifetime class instances and Derived class members
Diamond
Problem
Exercise
Design Choice
Summary
Summary k
Diamond
Problem
Exercise
Design Choice
Summary
Summary
2
NPTEL MOOCs Programming in C++ Partha Pratim Das 15
Multiple Inheritance in C++:
Object Lifetime
Module 35 class Base1 { protected: int i_; int data_;
public: Base1(int a, int b) : i_(a), data_(b) { cout << "Base1::Base1() "; }
Partha Pratim ~Base1() { cout << "Base1::~Base1() "; }
Das };
class Base2 { protected: int j_; int data_;
public:
Objectives & Base2(int a = 0, int b = 0) : j_(a), data_(b) { cout << "Base2::Base2() "; }
Outline ~Base2() { cout << "Base2::~Base2() "; }
};
Multiple
class Derived : public Base1, public Base2 { int k_;
Inheritance in
public:
C++
Derived(int x, int y, int z) :
Semantics Base1(x, y), k_(z) { cout << "Derived::Derived() "; }
Data Members
// Base1::Base1 explicit, Base2::Base2 default
Overrides and
Overloads ~Derived() { cout << "Derived::~Derived() "; }
protected };
Access
Constructor & Derived d(5, 3, 2);
Destructor
Object Lifetime
Construction O/P Destruction O/P
Diamond Base1::Base1(): 5, 3 // Obj. d.Base1 Derived::~Derived(): 2 // Obj. d
Problem Base2::Base2(): 0, 0 // Obj. d.Base2 Base2::~Base2(): 0, 0 // Obj. d.Base2
Exercise Derived::Derived(): 2 // Obj. d Base1::~Base1(): 3, 5 // Obj. d.Base1
Design Choice
• First construct base class objects, then derived class object
Summary • First destruct derived class object, then base class objects
Objectives &
Outline
Multiple
Inheritance in
C++
Semantics
Data Members
Overrides and
Overloads class Person; // Base Class = Person -- Root
protected class Student: public Person; // Base / Derived Class = Student
Access class Faculty: public Person; // Base / Derived Class = Faculty
Constructor &
Destructor class TA: public Student, public Faculty; // Derived Class = TA
Object Lifetime
Student inherits properties and operations of Person
Diamond
Problem Faculty inherits properties and operations of Person
Exercise TA inherits properties and operations of both Student as well as Faculty
Design Choice
TA, by transitivity, inherits properties and operations of Person
Summary
Design Choice
Summary
Summary
Objectives &
Outline
Multiple
Inheritance in
C++
Semantics
Data Members
Overrides and
Overloads
protected
Access
Constructor &
Destructor
Object Lifetime
Diamond
Wheeled Hierarchy and Engine Hierarchy interact
Problem
Exercise
Large number of cross links!
Design Choice Multiplicative options make modeling difficult
Summary
Objectives &
Outline
Multiple
Inheritance in
C++
Semantics
Data Members
Overrides and
Overloads
protected
Access
Constructor &
Destructor
Object Lifetime
Wheeled Hierarchy use Engine as Component
Diamond
Problem
Exercise
Linear options to simplify models
Design Choice Is this dominant?
Summary
Objectives &
Outline
Multiple
Inheritance in
C++
Semantics
Data Members
Overrides and
Overloads
protected
Access
Constructor &
Destructor
Object Lifetime
Diamond
Engine Hierarchy use Wheeled as Component
Problem
Exercise
Linear options to simplify models
Design Choice Is this dominant?
Summary
Module 35
Diamond
Problem
Exercise
Design Choice
Summary
Module 35
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Multiple
Srijoni Majumdar, TA [email protected] 9674474267
Inheritance in Himadri B G S Bhuyan, TA [email protected] 9438911655
C++
Semantics
Data Members
Overrides and
Overloads
protected
Access
Constructor &
Destructor
Object Lifetime
Diamond
Problem
Exercise
Design Choice
Summary
Partha Pratim
Das Module 36: Programming C++
Objective &
Outline
Exceptions (Error handling in C): Part 1
Exception
Fundamentals
Types of
Exceptions
Exception Stages
Partha Pratim Das
Exceptions in
C Department of Computer Science and Engineering
C Language Indian Institute of Technology, Kharagpur
Features
RV & Params
Local goto [email protected]
C Standard
Library Support
Global Variables
Abnormal Tanwi Mallick
Termination
Conditional Srijoni Majumdar
Termination Himadri B G S Bhuyan
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 1
Module Objectives
Module 36
Objective &
Outline
Exception
Fundamentals
Types of
Exceptions
Exception Stages
Exceptions in
C
C Language
Features
RV & Params
Local goto
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 2
Module Outline
Exception Fundamentals
Module 36
Types of Exceptions
Partha Pratim Exception Stages
Das
Exceptions in C
Objective & C Language Features
Outline
Exception
Return value & parameters
Fundamentals Local goto
Types of
Exceptions C Standard Library Support
Exception Stages
Global variables
Exceptions in Abnormal termination
C
C Language
Conditional termination
Features Non-local goto
RV & Params
Local goto
Signal
C Standard
Library Support Shortcomings
Global Variables
Abnormal Exceptions in C++
Termination
Conditional Exception Scope (try)
Termination
Non-Local goto
Exception Arguments (catch)
Signals Exception Matching
Shortcomings
Exception Raise (throw)
Summary Advantages
NPTEL MOOCs Programming in C++ Partha Pratim Das 3
What are Exceptions?
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Exception Causes
Module 36
Exceptions in
C
C Language
Features
RV & Params Exceptions are C++’s means of separating error reporting from
Local goto
C Standard error handling
Library Support
Global Variables – Bjarne Stroustrup
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Types of Exceptions
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Exception Stages
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Support for Exceptions in C
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Return Value & Parameters
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Example: Return Value & Parameters
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Local goto
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 13
Example: Local goto
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 14
Example: Local goto
Module 36
Partha Pratim
Das
Objective &
Outline
Exception
Fundamentals
Types of
Exceptions
Exception Stages
Exceptions in
C
C Language
Features
RV & Params
Local goto
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 15
Example: Local goto
Module 36
Partha Pratim
Das
Objective &
Outline
Exception
Fundamentals
Types of
Exceptions
Exception Stages
Exceptions in
C
C Language
Features
RV & Params
Local goto
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 16
Example: Local goto
Module 36
Partha Pratim
Das
Objective &
Outline
Exception
Fundamentals
Types of
Exceptions
Exception Stages
Exceptions in
C
C Language
Features
RV & Params
Local goto
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 17
Global Variables
Module 36
Exceptions in
C
C Language
Features
RV & Params
Local goto
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 18
Example: Global Variables
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 20
Example: Abnormal Termination
Module 36 #include<stdio.h>
#include<stdlib.h>
Partha Pratim
Das
static void atexit_handler_1(void) {
printf("within ’atexit_handler_1’ \n");
Objective & }
Outline
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 22
Example: Conditional Termination
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 23
Example: Conditional Termination
Module 36
Partha Pratim
Das
Objective &
Outline
Exception
Fundamentals
Types of
Exceptions
Exception Stages
Exceptions in
C
C Language
Features
RV & Params
Local goto
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 24
Example: Conditional Termination
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 25
Non-Local goto
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 26
Example: Non-Local goto: The Dynamics
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 27
Example: Non-Local goto
Module 36
Partha Pratim
Das
Objective &
Outline
Exception
Fundamentals
Types of
Exceptions
Exception Stages
Exceptions in
C
C Language
Features
RV & Params
Local goto
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination g() called
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 28
Example: Non-Local goto
Module 36
Partha Pratim
Das
Objective &
Outline
Exception
Fundamentals
Types of
Exceptions
Exception Stages
Exceptions in
C
C Language
Features
RV & Params
Local goto
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination g() successfully returns
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 29
Example: Non-Local goto
Module 36
Partha Pratim
Das
Objective &
Outline
Exception
Fundamentals
Types of
Exceptions
Exception Stages
Exceptions in
C
C Language
Features
RV & Params
Local goto
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination g() called and longjmp() executed
Non-Local goto
Signals
Shortcomings
setjmp() takes to exception part
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 30
Example: Non-Local goto
Module 36 #include<setjmp.h>
Partha Pratim
#include<stdio.h>
Das jmp_buf j ;
void raise_exception(){
Objective & printf("Exception raised \n");
Outline longjmp(j, 1) ; /* Jump to exception handler */
Exception printf("This line should never appear \n");
Fundamentals }
Types of
Exceptions int main(){
Exception Stages if (setjmp == 0) {
Exceptions in printf(" ’setjmp’ is intializing j \n ");
C raise_exception();
C Language
Features printf("This line should never appear \n");
RV & Params }
Local goto
C Standard else
Library Support printf(" ’setjmp’ was just jumped into \n")
Global Variables
Abnormal /* This code is the exception handler */
Termination
Conditional
return 0 ;
Termination }
Non-Local goto
Signals
/* On execution : ’setjmp’ is intializing j ,
Shortcomings exception raised and ’setjmp’ was just jumped into */
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 31
Signals
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 32
Example: Signals
Module 36
Partha Pratim
// Use signal to attach a signal
Das // handler to the abort routine
#include <stdio.h>
Objective & #include <stdlib.h>
Outline
#include <signal.h>
Exception #include <tchar.h>
Fundamentals void SignalHandler(int signal) {
Types of
Exceptions printf("Application aborting...\n");
Exception Stages }
Exceptions in
C int main() {
C Language
Features typedef void (*SignalHandlerPointer)(int);
RV & Params
Local goto
C Standard SignalHandlerPointer previousHandler;
Library Support
Global Variables
Abnormal previousHandler = signal(SIGABRT, SignalHandler);
Termination
Conditional
Termination abort();
Non-Local goto
Signals
Shortcomings return 0;
Summary }
NPTEL MOOCs Programming in C++ Partha Pratim Das 33
Shortcomings
Module 36
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 34
Module Summary
Module 36
Exceptions in
C
C Language
Features
RV & Params
Local goto
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 35
Instructor and TAs
Module 36
Partha Pratim
Das Name Mail Mobile
Objective &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Exception
Srijoni Majumdar, TA [email protected] 9674474267
Fundamentals Himadri B G S Bhuyan, TA [email protected] 9438911655
Types of
Exceptions
Exception Stages
Exceptions in
C
C Language
Features
RV & Params
Local goto
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 36
Module 37
Partha Pratim
Das Module 37: Programming C++
Objective &
Outline
Exceptions (Error handling in C++): Part 2
Exceptions in
C++
Exception Scope
(try)
Exception
Partha Pratim Das
Arguments
(catch)
Exception Department of Computer Science and Engineering
Matching
Exception Raise Indian Institute of Technology, Kharagpur
(throw)
Advantages [email protected]
Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 37
Objective &
Outline
Exceptions in
C++
Exception Scope
(try)
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages
Summary
Exceptions in
Return value & parameters
C++ Local goto
Exception Scope
(try) C Standard Library Support
Exception
Arguments Global variables
(catch)
Exception
Abnormal termination
Matching Conditional termination
Exception Raise
(throw) Non-local goto
Advantages Signal
Summary
Shortcomings
Exceptions in C++
Exception Scope (try)
Exception Arguments (catch)
Exception Matching
Exception Raise (throw)
Advantages
NPTEL MOOCs Programming in C++ Partha Pratim Das 3
Expectations
Module 37
Summary
Module 37
Partha Pratim
Das
Objective &
Outline
Exceptions in
C++
Exception Scope
(try)
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages
Summary
g() called
Module 37
Partha Pratim
Das
Objective &
Outline
Exceptions in
C++
Exception Scope
(try)
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages
Summary
Module 37
Partha Pratim
Das
Objective &
Outline
Exceptions in
C++
Exception Scope
(try)
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages
Summary
Objective &
function try block
Outline
Area for detection is the entire function body
Exceptions in
C++
Exception Scope
Nested try block
(try)
Exception
Arguments
Semantically equivalent to nested function calls
(catch)
Exception
Matching
Exception Raise
(throw) Function try Nested try
Advantages
Summary
void f() try {
try { try { throw E(); }
throw E(); catch (E& e) { }
} }
catch (E& e) { catch (E& e1) {
} }
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
try-throw-catch
Module 37
Partha Pratim
Das
Objective &
Outline
Exceptions in
C++
Exception Scope
(try)
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages
Summary
try Block
Summary
Module 37
Partha Pratim
Das
Objective &
Outline
Exceptions in
C++
Exception Scope
(try)
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages
Summary
catch Block
Module 37
Partha Pratim
Das
Objective &
Outline
Exceptions in
C++
Exception Scope
(try)
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages
Summary
Expression Matching
Summary
Or, Copies an existing Exception object to throw
Exception ex;
...
throw ex; // Exception(ex);
Module 37
Partha Pratim
Das
Objective &
Outline
Exceptions in
C++
Exception Scope
(try)
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages
Summary
throw Expression
Objective &
The type of Expression cannot be
Outline
An incomplete type (like void, array of unknown size or of
Exceptions in
C++ elements of incomplete type, Declared but not Defined
Exception Scope
(try)
struct / union / enum / class Objects or Pointers to
Exception
Arguments such Objects)
(catch)
Exception A pointer to an Incomplete type, except void*, const
Matching
Exception Raise void*, volatile void*, const volatile void*
(throw)
Advantages
Summary
Module 37 Re-throw
Partha Pratim
Das
catch may pass on the exception after handling
Re-throw is not same as throwing again!
Objective &
Outline
Exceptions in
C++
Throws again Re-throw
Exception Scope try { ... } try { ... }
(try)
Exception
Arguments
catch (Exception& ex) { catch (Exception& ex) {
(catch)
Exception
// Handle and // Handle and
Matching
Exception Raise ... ...
(throw)
Advantages // Raise again // Pass-on
Summary
throw ex; throw;
// ex copied // No copy
// ex destructed // No Destruction
} }
Module 37
Summary
Native and Standard:
EH is part of the C++ language
EH is available in all standard C++ compilers
Module 37
Module 37
Summary
Module 37
Partha Pratim
Das Name Mail Mobile
Objective &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Exceptions in
Srijoni Majumdar, TA [email protected] 9674474267
C++ Himadri B G S Bhuyan, TA [email protected] 9438911655
Exception Scope
(try)
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages
Summary
Partha Pratim
Das Module 38: Programming in C++
Objectives &
Outline
Template (Function Template): Part 1
What is a
Template?
Function
Template
Partha Pratim Das
Definition
Instantiation
Department of Computer Science and Engineering
Template
Argument Indian Institute of Technology, Kharagpur
Deduction
Example
[email protected]
typename
Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 38
Objectives &
Outline
What is a
Template?
Function
Template
Definition
Instantiation
Template
Argument
Deduction
Example
typename
Summary
Module 38
Module 38
int main() {
Objectives & int a = 3, b = 5;
Outline double c = 2.1, d = 3.7;
What is a
cout << "Max(" << a << ", " << b << ") = " << Max(a, b) << endl;
Template?
// Output: Max(3, 5) = 5
Function
Template cout << "Max(" << c << ", " << d << ") = " << Max(c, d) << endl;
// Output: Max(2.1, 3.7) = 3.7
Definition
Instantiation
Template
return 0;
Argument }
Deduction
Example • Max, being a macro, is type oblivious – can be used for int as well as double, etc.
• Note the parentheses around parameters to protect precedence
typename • Note the parentheses around the whole expression to protect precedence
• Looks like a function – but does not behave as such
Summary
return 0;
}
• In ”Side Effects” – the result is wrong, the larger values gets incremented twice
• In ”C-String Comparison” – swapping parameters changes the result – actually compares pointers
NPTEL MOOCs Programming in C++ Partha Pratim Das 8
Function Template
Summary return 0;
}
• Generic template code does not work for C-Strings as it compares pointers, not the strings pointed by them
• We provide a specialization to compare pointers using comparison of strings
• Need to specify type explicitly is bothersome
• Often template type parameter T may be inferred from the type of parameters in the instance
• If the compiler cannot infer or infers wrongly, we use explicit instantiation
• When Max is instantiated with class Complex, we need comparison operator for Complex
• The code, therefore, will not compile without bool operator>(const Complex&, const Complex&)
• Traits of type variable T include bool operator>(T, T) which the instantiating type must fulfill
Objectives & template<> char *Max<char *>(char *x, char *y) { return strcmp(x, y) > 0 ? x : y; }
Outline
template<class T, int size> T Max(T x[size]) { T t = x[0];
What is a
for (int i = 0; i < size; ++i) { if (x[i] > t) t = x[i]; }
Template?
Function return t;
Template }
Definition
int main() {
Instantiation
Template
int arr[] = { 2, 5, 6, 3, 7, 9, 4 };
Argument cout << "Max(arr) = " << Max<int, 7>(arr) << endl; // Output: Max(arr) = 9
Deduction
Example return 0;
typename }
Summary return 0;
}
Module 38 Consider:
Partha Pratim template <class T> f (T x) {
Das
T::name * p;
Objectives &
}
Outline
What does it mean?
What is a
Template? T::name is a type and p is a pointer to that type
Function
T::name and p are variables and this is a multiplication
Template
Definition
To resolve, we use keyword typename:
Instantiation
Template template <class T> f (T x) { T::name * p; } // Multiplication
Argument
Deduction
Example template <class T> f (T x) { typename T::name * p; } // Type
typename
The keywords class and typename have almost the same meaning in a
Summary template parameter
typename is also used to tell the compiler that an expression is a type
expression
Module 38
typename
Summary
Module 38
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
What is a
Srijoni Majumdar, TA [email protected] 9674474267
Template? Himadri B G S Bhuyan, TA [email protected] 9438911655
Function
Template
Definition
Instantiation
Template
Argument
Deduction
Example
typename
Summary
Partha Pratim
Das Module 39: Programming in C++
Objectives &
Outline
Template (Class Template): Part 2
What is a
Template?
Function
Template
Partha Pratim Das
Class
Template Department of Computer Science and Engineering
Definition Indian Institute of Technology, Kharagpur
Instantiation
Partial Template
Instantiation &
[email protected]
Default
Template
Parameters
Inheritance Tanwi Mallick
Summary Srijoni Majumdar
Himadri B G S Bhuyan
Module 39
Objectives &
Outline
What is a
Template?
Function
Template
Class
Template
Definition
Instantiation
Partial Template
Instantiation &
Default
Template
Parameters
Inheritance
Summary
Module 39
Class typename
Template
Definition
Class Template
Instantiation
Partial Template Class Template Definition
Instantiation &
Default Instantiation
Template
Parameters
Inheritance
Partial Template Instantiation & Default Template
Summary
Parameters
Inheritance
Summary
Summary
return 0;
}
Class
Template
Definition
Instantiation
Partial Template
Instantiation &
Default
Template
Parameters
Inheritance
Summary
Summary
#include <vector>
Partha Pratim
using namespace std;
Das
template<class T>
Objectives & class List {
Outline public:
void put(const T &val) { items.push_back(val); }
What is a int length() { return items.size(); }
Template? bool find(const T &val) {
for (unsigned int i = 0; i < items.size(); ++i)
Function if (items[i] == val) return true;
Template return false;
Class }
Template private:
vector<T> items;
Definition
};
Instantiation
Partial Template
Instantiation & #endif // __LIST_H
Default
Template • List is basic container class
Parameters
Inheritance
Summary
#include "List.h"
Partha Pratim
Das
template<class T>
class Set {
Objectives & public:
Outline Set() { };
virtual void add(const T &val);
What is a int length();
Template? bool find(const T &val);
private:
Function List<T> items;
Template };
Class
Template template<class T>
void Set<T> :: add(const T &val)
Definition
{
Instantiation
if (items.find(val)) return;
Partial Template
Instantiation & items.put(val);
Default }
Template
Parameters template<class T> int Set<T> :: length() { return items.length(); }
Inheritance template<class T> bool Set<T> ::find(const T &val) { return items.find(val); }
#endif // __SET_H
Summary
• Set is a base class for a set
• Set uses List for container
#include "Set.h"
Partha Pratim
Das
template<class T>
class BoundSet : public Set<T> {
Objectives & public:
Outline BoundSet(const T &lower, const T &upper);
void add(const T &val);
What is a private:
Template? T min;
T max;
Function };
Template
Module 39
Summary
Module 39
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
What is a
Srijoni Majumdar, TA [email protected] 9674474267
Template? Himadri B G S Bhuyan, TA [email protected] 9438911655
Function
Template
Class
Template
Definition
Instantiation
Partial Template
Instantiation &
Default
Template
Parameters
Inheritance
Summary
Partha Pratim
Das Module 40: Programming C++
Objectives & Closing Comments
Outline
Course
Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan
Module 40
Key Take-back
Prepare for
Examination
Road Forward
Summary
Module 40
Prepare for
Examination
Road Forward
Summary
Road Forward
Polymorphism: Static and Dynamic Binding, Virtual
Summary
Function Table, Multiple Inheritance
Type Casting: Cast Operators
Exceptions: Error Handling in C & C++
Templates: Generic Programming in C++
Module 40
C++ is multi-paradigm
Partha Pratim
Das Procedural: Better C
Object-Oriented: Encapsulation, Inheritance, and Polymorphism
Objectives & Generic: Templates
Outline
Module 40
Watch the Videos
Partha Pratim
Das Revise the Assignments and Solutions
Practice lots and lots of coding with every feature
Objectives &
Outline Design and implement complete data types – Complex, Fraction, Vector,
Course Matrix, Polynomial etc.
Summary
Study Books, try examples
Key Take-back
The C++ Programming Language by Bjarne Stroustrup
Prepare for Effective C++ & More Effective C++ by Scott Meyers
Examination
Road Forward
Summary
Module 40
Learn the topics not covered
Partha Pratim
Das Breathe programming – regularly code and implement systems
Read lots and lots of programs by good coders
Objectives &
Outline Learn Python / Java
Course Study Object Oriented Analysis and Design
Summary
Study Unified Modeling Language
Key Take-back
Study Software Engineering
Prepare for
Examination Study Books
Road Forward The C++ Programming Language by Bjarne Stroustrup
Summary Effective C++ & More Effective C++ by Scott Meyers
Exceptional C++ & More Exceptional C++ by Herb Sutter
Modern C++ Design by Andrei Alexandrescu
Design Patterns: Elements of Reusable Object-Oriented Software by
Erich Gamma, Richard Helm, Ralph Johnson, & John Vlissides
Learning UML 2.0 – A Pragmatic Introduction to UML by Russ Miles
& Kim Hamilton (O’Reilly)
Module 40
Objectives &
Outline
Course
Summary
Key Take-back
Prepare for
Examination
Road Forward
Summary
Module 40
Partha Pratim
Das Name Mail Mobile
Objectives &
Partha Pratim Das, Instructor [email protected] 9830030880
Outline Tanwi Mallick, TA [email protected] 9674277774
Course
Srijoni Majumdar, TA [email protected] 9674474267
Summary Himadri B G S Bhuyan, TA [email protected] 9438911655
Key Take-back
Prepare for
Examination
Road Forward
Summary