0% found this document useful (0 votes)
14 views723 pages

C++ Modules

Uploaded by

Daksh Deshlan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views723 pages

C++ Modules

Uploaded by

Daksh Deshlan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 723

Module 01

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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 01

Partha Pratim Revisit the concepts of C language


Das
Revisit C Standard Library components
Objectives &
Outline Revisit the Organization and Build Process for C programs
Recap of C
Data Types
Create the foundation for the concepts of C++ with
Variables
Literals
backward compatibility to C
Operators
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output

Std Library

Organization

Build Process

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 01 Recap of C features


Partha Pratim Data types
Das Variables
Objectives &
Literals
Outline Operators
Recap of C Expressions
Data Types
Variables Statements
Literals
Operators
Control Constructs – Conditional Flow & Loops
Expressions
Statements
Arrays
Control Flow Structures & Unions
Arrays
Structures Pointers
Unions
Pointers Functions
Functions
Input / Output
Input / Output
Std Library C Standard Library
Organization
Source Organization for a C program
Build Process

References Build Process


Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 3
Module 01: Lecture 01

Module 01 Recap of C features


Partha Pratim Data types
Das Variables
Objectives &
Literals
Outline Operators
Recap of C Expressions
Data Types
Variables Statements
Literals
Operators
Control Constructs – Conditional Flow & Loops
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output

Std Library

Organization

Build Process

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 4


First C program

Module 01

Partha Pratim Print ”Hello World”


Das
Source Program
Objectives &
Outline #include <stdio.h>

Recap of C int main() {


Data Types
Variables printf("Hello World");
Literals printf("\n");
Operators
Expressions return 0;
Statements }
Control Flow
Arrays
Structures • stdio.h header included for input / output
Unions • main function is used to start execution
Pointers • printf function is used to print the string ”Hello World”
Functions
Input / Output

Std Library

Organization

Build Process

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Data Types

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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Data Types

Module 01 Data types in C further include:


Partha Pratim void: The type specifier void indicates no type.
Das

Derived data types include:


Objectives &
Outline
Array
Recap of C
Data Types
Structure – struct & union
Variables Pointer
Literals
Operators Function
Expressions
Statements String – C-Strings are really not a type; but can be made
Control Flow
Arrays
to behave as such using functions from <string.h> in
Structures
Unions
standard library
Pointers
Functions Type modifiers include:
Input / Output

Std Library short


Organization long
Build Process signed
References unsigned
Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Variables

Module 01 A variable is a name given to a storage area


Partha Pratim
Das Declaration of Variables:

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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Variables

Module 01 Initialization of Variables:


Partha Pratim
Das
Initialization is setting an initial value to a variable at its
definition
Objectives &
Outline

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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Literals

Module 01

Partha Pratim Literals refer to fixed values of a built-in type


Das
Literals can be of any of the basic data types
Objectives &
Outline 212 // (int) Decimal literal
0173 // (int) Octal literal
Recap of C 0b1010 // (int) Binary literal
Data Types 0xF2 // (int) Hexadecimal literal
Variables 3.14 // (double) Floating-point literal
Literals ’x’ // (char) Character literal
Operators "Hello" // (char *) String literal
Expressions
Statements
Control Flow In C99, literals are constant values having const types as:
Arrays
Structures
212 // (const int) Decimal literal
Unions
0173 // (const int) Octal literal
Pointers
Functions
0b1010 // (const int) Binary literal
Input / Output 0xF2 // (const int) Hexadecimal literal
3.14 // (const double) Floating-point literal
Std Library ’x’ // (const char) Character literal
"Hello" // (const char *) String literal
Organization

Build Process

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Operators

Module 01 An operator denotes a specific operation. C has the following


Partha Pratim types of operators:
Das
Arithmetic Operators: + – * / % ++ – –
Objectives & Relational Operators: == != > < >= <=
Outline Logical Operators: && || !
Recap of C Bit-wise Operators: & | ˜ << >>
Data Types Assignment Operators: = += –= *= /= · · ·
Variables
Literals
Miscellaneous Operators: . , sizeof & * ?:
Operators
Expressions
Statements
Arity of Operators: Number of operand(s) for an operator
Control Flow
Arrays
+, –, *, & operators can be unary (1 operand) or binary (2 operands)
Structures ==, !=, >, <, >=, <=, &&, ||, +=, –=, *=, =, /=, &, |, <<,
Unions >> can work only as binary (2 operands) operators
Pointers
Functions sizeof ! ˜ ++ – – can work only as unary (1 operand) operators
Input / Output
?: works as ternary (3 operands) operator. The condition is the first
Std Library
operand and the if true logic and if false logic corresponds to the
Organization
other two operands.
Build Process

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Operators

Module 01 Operator Precedence: Determines which operator will be


Partha Pratim performed first in a chain of different operators
Das The precedence of all the operators mentioned above is in the
following order: (left to right – Highest to lowest precedence)
Objectives &
Outline (), [], ++, –, + (unary), –(unary), !˜, *, &, sizeof, *, /, %, +, –, <
Recap of C
<, > >, ==, !=, *=, =, /=, &, |, &&, | |, ?:, =, +=, –=, *=, =,
Data Types /=, < <=, > >=
Variables
Literals
Operators Operator Associativity: Indicates in what order operators of
Expressions
Statements
equal precedence in an expression are applied
Control Flow
Arrays
Structures
Consider the expression a ˜ b ˜ c. If the operator ˜ has left
Unions associativity, this expression would be interpreted as (a ˜ b) ˜ c.
Pointers
Functions If the operator has right associativity, the expression would be
Input / Output
interpreted as a ˜ (b ˜ c).
Std Library
Right-to-Left: ?:, =, +=, -=, *=, =, /=, <<=, >>=, –, +-, !˜, *,
Organization
&, sizeof
Build Process
Left-to-Right: *, /, %, +, -, <<, >>, ==, !=, *=, =, /=, &, |,
References &&, | |
Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Expressions

Module 01 Every expression has a value


Partha Pratim
Das
A literal is an expression
A variable is an expression
Objectives & One, two or three expression/s connected by an operator
Outline

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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Statement

Module 01 A statement is a command for a specific action. It has no value


Partha Pratim A ; (semicolon) is a (null) statement
Das
An expression terminated by a ; (semicolon) is a statement
Objectives & A list of one or more statements enclosed within a pair of
Outline curly braces { and } or block is a compound statement
Recap of C Control constructs like if, if-else, switch, for, while,
Data Types
Variables do-while, goto, continue, break, return are
Literals
Operators statements
Expressions
Statements Example: Expression statements
Control Flow
Arrays Expressions Statements
Structures
i + j i + j;
Unions
k = i + j k = i + j;
Pointers funct(i,j) funct(i,j);
Functions k = funct(i,j) k = funct(i,j);
Input / Output
Example: Compound statements
Std Library {
Organization int i = 2, j = 3, t;

Build Process t = i;
i = j;
References j = t;
}
Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 14
Control Constructs

Module 01 These statements control the flow based on conditions:


Partha Pratim
Das
Selection-statement: if, if-else, switch
Labeled-statement: Statements labeled with identifier,
Objectives & case, or default
Outline

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 int sum = 0; while (n) { int f(int x, int y)


for(i = 0; i < 5; ++i) { sum += n; {
Organization int j = i * i; if (sum > 20) return x + y;
sum += j; break; }
Build Process } --n;
}
References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Module 01: End of Lecture 01

Module 01 Recap of C features


Partha Pratim Data types
Das Variables
Objectives &
Literals
Outline Operators
Recap of C Expressions
Data Types
Variables Statements
Literals
Operators
Control Constructs – Conditional Flow & Loops
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output

Std Library

Organization

Build Process

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 16


Module 01: Lecture 02

Module 01 Recap of C features


Partha Pratim Arrays
Das Structures
Objectives &
Unions
Outline Pointers
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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Arrays

Module 01 An array is a collection of data items, all of the same type,


Partha Pratim accessed using a common name
Das
Declare Arrays:
#define SIZE 10
Objectives & int name[SIZE]; // SIZE must be an integer constant greater than zero
Outline double balance[10];
Recap of C
Data Types
Initialize Arrays:
Variables int primes[5] = {2, 3, 5, 7, 11}; // Size = 5
Literals
Operators int primes[] = {2, 3, 5, 7, 11};
Expressions int sizeOfPrimes = sizeof(primes)/sizeof(int); // size is 5 by initialization
Statements
Control Flow int primes[5] = {2, 3}; // Size = 5, last 3 elements set to 0
Arrays
Structures Access Array elements:
Unions
int primes[5] = {2, 3};
Pointers
int EvenPrime = primes[0]; // Read 1st element
Functions
primes[2] = 5; // Write 3rd element
Input / Output

Std Library Multidimensional Arrays:


int mat[3][4];
Organization

Build Process for(i = 0; i < 3; ++i)


for(j = 0; j < 4; ++j)
References mat[i][j] = i + j;

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 18


Structures

Module 01 A structure is a collection of data items of different types. Data


Partha Pratim items are called members. The size of a structure is the sum of
Das the size of its members.
Objectives &
Declare Structures:
struct Complex { // Complex Number
Outline
double re; // Real component
Recap of C double im; // Imaginary component
} c; // c is a variable of struct Complex type
Data Types
printf("size = %d\n", sizeof(struct Complex)); // Prints: size = 16
Variables
Literals
Operators typedef struct _Books {
Expressions char title[50]; // data member
Statements char author[50]; // data member
Control Flow int book_id; // data member
Arrays } Books; // Books is an alias for struct _Books type
Structures
Unions Initialize Structures:
Pointers struct Complex x = {2.0, 3.5}; // Both members
Functions struct Complex y = {4.2}; // Only the first member
Input / Output

Std Library Access Structure members:


struct Complex x = {2.0, 3.5};
Organization double norm = sqrt(x.re*x.re + x.im*x.im); // Using . (dot) operator
Build Process
Books book;
References book.book_id = 6495407;
strcpy(book.title, "C Programming");
Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 19
Unions

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

Module 01 A pointer is a variable whose value is a memory address


Partha Pratim
Das
The type of a pointer is determined by the type of its pointee
int *ip; // pointer to an integer
Objectives & double *dp; // pointer to a double
Outline float *fp; // pointer to a float
char *ch // pointer to a character
Recap of C
Data Types
Variables Using a pointer:
Literals
Operators int main() {
Expressions int i = 20; // variable declaration
Statements int *ip; // pointer declaration
Control Flow ip = &i; // store address of i in pointer
Arrays
Structures
printf("Address of variable: %p\n", &i); // Prints: Address of variable : 00A8F73C
Unions
Pointers
Functions
printf("Value of pointer: %p\n", ip); // Prints: Value of pointer : 00A8F73C
Input / Output
printf("Value of pointee: %d\n", *ip); // Prints: Value of pointee : 20
Std Library
return 0;
Organization }
Build Process

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 21


Pointers

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

Module 01 Recap of C features


Partha Pratim Arrays
Das Structures
Objectives &
Unions
Outline Pointers
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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 23


Module 01: Lecture 03

Module 01 Recap of C features


Partha Pratim Functions
Das Input / Output
Objectives & C Standard Library
Outline

Recap of C Source Organization for a C program


Data Types
Variables Build Process
Literals
Operators
Expressions
Statements
Control Flow
Arrays
Structures
Unions
Pointers
Functions
Input / Output

Std Library

Organization

Build Process

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 24


Functions

Module 01 A function performs a specific task or computation


Partha Pratim Has 0, 1, or more parameters / arguments. Every
Das argument has a type (void for no argument)
Objectives &
May or may not return a result. Return value has a type
Outline (void for no result)
Recap of C Function declaration:
Data Types
Variables // Function Prototype / Header / Signature
Literals // Name of the function: funct
Operators // Parameters: x and y. Types of parameters: int
Expressions // Return type: int
Statements
Control Flow
int funct(int x, int y);
Arrays
Structures
Unions Function definition:
Pointers
Functions // Function Implementation
Input / Output int funct(int x, int y)
Std Library
// Function Body
Organization {
return (x + y);
Build Process }

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 25


Functions

Module 01 Call-by-value mechanism for passing arguments. The value of


Partha Pratim
an actual parameter copied to the formal parameter
Das
Return-by-value mechanism to return the value, if any.
Objectives & int funct(int x, int y) {
Outline ++x; ++y; // Formal parameters changed
return (x + y);
Recap of C
}
Data Types
Variables int main() {
Literals
int a = 5, b = 10, z;
Operators
Expressions
printf("a = %d, b = %d\n", a, b); // prints: a = 5, b = 10
Statements
Control Flow
Arrays
z = funct(a, b); // function call by value
Structures // a copied to x. x becomes 5
Unions // b copied to y. y becomes 10
Pointers // x in funct changes to 6 (++x)
Functions // y in funct changes to 11 (++y)
Input / Output // return value (x + y) copied to z

Std Library printf("funct = %d\n", z); // prints: funct = 17


Organization
// Actual parameters do not change on return (call-by-value)
Build Process printf("a = %d, b = %d\n", a, b); // prints: a = 5, b = 10

References return 0;
}
Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 26
Functions

Module 01 A function may be recursive (call itself)


Partha Pratim
Das
Has recursive step/s
Has exit condition/s
Objectives &
Outline Example:
Recap of C
// Factorial of n
Data Types
unsigned int factorial(unsigned int n) {
Variables
if (n > 0)
Literals
return n * factorial(n - 1); // Recursive step
Operators
else
Expressions
Statements
return 1; // Exit condition
Control Flow }
Arrays
Structures // Number of 1’s in the binary representation of n
Unions unsigned int nOnes(unsigned int n) {
Pointers if (n == 0)
Functions return 0; // Exit condition
Input / Output else // Recursive steps
if (n % 2 == 0)
Std Library return nOnes(n / 2);
else
Organization
return nOnes(n / 2) + 1;
Build Process }

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 27


Function pointers

Module 01 #include <stdio.h>


DrawFunc DrawArr[] = { // Array of func. ptrs
struct GeoObject {
drawCir, drawRec, drawTrg };
Partha Pratim enum { CIR = 0, REC, TRG } gCode;
Das union {
int main() {
struct Cir { double x, y, r; } c;
struct GeoObject go;
struct Rec { double x, y, w, h; } r;
Objectives & struct Trg { double x, y, b, h; } t;
Outline go.gCode = CIR;
};
go.c.x = 2.3; go.c.y = 3.6;
};
Recap of C go.c.r = 1.2;
Data Types DrawArr[go.gCode](go); // Call by ptr
typedef void(*DrawFunc) (struct GeoObject);
Variables
Literals go.gCode = REC;
void drawCir(struct GeoObject go) {
Operators go.r.x = 4.5; go.r.y = 1.9;
printf("Circle: (%lf, %lf, %lf)\n",
Expressions go.r.w = 4.2; go.r.h = 3.8;
go.c.x, go.c.y, go.c.r); }
Statements DrawArr[go.gCode](go); // Call by ptr
Control Flow
Arrays
void drawRec(struct GeoObject go) {
go.gCode = TRG;
Structures printf("Rect: (%lf, %lf, %lf, %lf)\n",
go.t.x = 3.1; go.t.y = 2.8;
Unions go.r.x, go.r.y, go.r.w, go.r.h); }
go.t.b = 4.4; go.t.h = 2.7;
Pointers DrawArr[go.gCode](go); // Call by ptr
Functions void drawTrg(struct GeoObject go) {
Input / Output printf("Triag: (%lf, %lf, %lf, %lf)\n",
return 0;
go.t.x, go.t.y, go.t.b, go.t.h); }
Std Library }

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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 28


Input / Output

Module 01 int printf(const char *format, ...) writes to stdout


Partha Pratim by the format and returns the number of characters written
Das
int scanf(const char *format, ...) reads from stdin
Objectives &
Outline
by the format and returns the number of characters read
Recap of C Use %s, %d, %c, %lf, to print/scan string, int, char, double
Data Types
Variables #include <stdio.h>
Literals
Operators
int main() {
Expressions
Statements
char str[100];
Control Flow
int i;
Arrays
Structures
Unions printf("Enter a value :"); // prints a constant string
Pointers
Functions scanf("%s %d", str, &i); // scans a string value and an integer value
Input / Output
printf("You entered: %s %d ", str, i); // prints string and integer
Std Library
return 0;
Organization }
Build Process

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 29


Input / Output

Module 01
To write to or read from file:
Partha Pratim #include <stdio.h>
Das
int main() {

Objectives & FILE *fp = NULL;


Outline int i;
Recap of C fp = fopen("Input.dat", "r");
Data Types fscanf(fp, "%d", &i); // scan from Input.dat
Variables fclose(fp);
Literals
Operators fp = fopen("Output.dat", "w");
Expressions
fprintf("%d^2 = %d\n", i, i*i); // prints to Output.dat
Statements
fclose(fp);
Control Flow
Arrays
return 0;
Structures
Unions
}
Pointers
Functions
Input / Output

Std Library

Organization

Build Process

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 30


C Standard Library

Common Library Components:


Module 01

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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 32


Source Organization for a C program

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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 33


Build Flow

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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 34


Build Process

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; }

Build Process int main() {


int a = sum(1,2); // as files are linked, uses functions directly
References return a;
}
Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 35
Tools

Module 01

Partha Pratim Development IDE: Code::Blocks 16.01


Das
Compiler: -std=c++98 and -std=c99
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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 36


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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 37


Module Summary

Module 01

Partha Pratim Revised the concept of variables and literals in C


Das
Revised the various data types and operators of C
Objectives &
Outline Re-iterated through the control constructs of C
Recap of C
Data Types
Re-iterated through the concepts of functions and pointers
Variables
Literals
of C
Operators
Expressions Re-iterated through the program organization of C and the
Statements
Control Flow build process.
Arrays
Structures
Unions
Pointers
Functions
Input / Output

Std Library

Organization

Build Process

References

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 38


Instructor and TAs

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

Summary of NPTEL MOOCs Programming in C++ Partha Pratim Das 39


Module 02

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 02

Partha Pratim Understand differences between C and C++ programs


Das
Appreciate the ease of programming in C++
Objectives &
Outline
Hello World
Add numbers
Square Root
Standard Library
Sum Numbers
Using bool

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 02

Partha Pratim Contrast differences between C and C++ programs for:


Das
I/O
Objectives & Variables
Outline
Hello World
Using math library
Add numbers Standard Library – Headers
Square Root
Standard Library Loop
Sum Numbers
Using bool bool type
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Program 02.01: Hello World

Module 02 C Program C++ Program

Partha Pratim // FileName:HelloWorld.c: // FileName:HelloWorld.cpp:


Das #include <stdio.h> #include <iostream>

int main() { int main() {


Objectives &
Outline printf("Hello World in C"); std::cout << "Hello World in C++";
Hello World printf("\n"); std::cout << std::endl;
Add numbers
Square Root return 0; return 0;
Standard Library
} }
Sum Numbers
Using bool

Summary Hello World in C Hello World in C++

• IO Header is stdio.h • IO Header is iostream


• printf to print to console • operator<< to stream to console
• Console is stdout file • Console is std::cout ostream (in std namespace)
• printf is a variadic function • operator<< is a binary operator
• \n to go to the new line • std::endl (in std namespace) to go to the new line
• \n is escaped newline character • std::endl is stream manipulator (newline) functor

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Program 02.02: Add two numbers
C Program C++ Program
Module 02
// FileName:Add_Num.c: // FileName:Add_Num_c++.cpp:
Partha Pratim #include <stdio.h> #include <iostream>
Das int main() { int main() {
int a, b; int a, b;
Objectives & int sum;
Outline
printf("Input two numbers:\n"); std::cout << "Input two numbers:\n";
Hello World
scanf("%d%d", &a, &b); std::cin >> a >> b;
Add numbers
Square Root
sum = a + b; int sum = a + b; // Declaration of sum
Standard Library
Sum Numbers
Using bool printf("Sum of %d and %d", a, b); std::cout << "Sum of "
printf(" is: %d\n", sum); << a << " and "
Summary << b << " is: "
return 0; << sum << std::endl;
}
return 0;
}
Input two numbers: Input two numbers:
34 34
Sum of 3 and 4 is: 7 Sum of 3 and 4 is: 7

• scanf to scan (read) from console • operator>> to stream from console


• Console is stdin file • Console is std::cin istream (in std namespace)
• scanf is a variadic function • operator>> is a binary operator
• Addresses of a and b needed in scanf • a and b can be directly used in operator>> operator
• All variables a, b & sum declared first (C89) • sum may be declared when needed
• Formatting (%d) needed for variables • Formatting is derived from type (int) of variables

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Program 02.03: Square Root of a number
C Program C++ Program
Module 02
// FileName:Sqrt.c: // FileName:Sqrt_c++.cpp:
Partha Pratim #include <stdio.h> #include <iostream>
Das #include <math.h> #include <cmath>
using namespace std;
Objectives &
int main() { int main() {
Outline
double x; double x;
Hello World
double sqrt_x;
Add numbers
Square Root
printf("Input number:\n"); cout << "Input number:" << endl;
Standard Library
Sum Numbers
scanf("%lf", &x); cin >> x;
Using bool
sqrt_x = double sqrt_x = // Declaration of sqrt_x
Summary sqrt(x); sqrt(x);

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)

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


namespace std for C++ Standard Library

Module 02 C Standard Library C++ Standard Library

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

Summary W/o using W/ using


#include <iostream> #include <iostream>
using namespace std;

int main() { int main() {

std::cout << "Hello World in C++" cout << "Hello World in C++"
<< std::endl; << endl;

return 0; return 0;
} }

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Standard Library Header Conventions

Module 02

Partha Pratim C Header C++ Header


Das C Program Use .h. Example: Not applicable
#include <stdio.h>
Names in global namespace
Objectives &
C++ Program Prefix c, no .h. Example: No .h. Example:
Outline
#include <cstdio> #include <iostream>
Hello World
Names in std namespace
Add numbers
Square Root
Standard Library
Sum Numbers
Using bool
Any C standard library header is to be used in C++ with a prefix ’c’ and
without the .h. These symbols will be in std namespace. Like:
Summary
#include <cmath> // In C it is <math.h>
...
std::sqrt(5.0); // Use with std::
It is possible that a C++ program include a C header as in C. Like:
#include <math.h> // Not in std namespace
...
sqrt(5.0); // Use without std::

This, however, is not preferred.


Using .h with C++ header files, like iostream.h, is disastrous. These
are deprecated. It is dangerous, yet true, that some compilers do not
error out on such use. Exercise caution.
NPTEL MOOCs Programming in C++ Partha Pratim Das 8
Program 02.04: Sum n natural numbers

Module 02 C Program C++ Program

Partha Pratim // FileName:Sum_n.c: // FileName:Sum_n_c++.cpp:


Das #include <stdio.h> #include <iostream>
using namespace std;
Objectives & int main() { int main() {
Outline int n; int n;
Hello World int i;
Add numbers int sum = 0; int sum = 0;
Square Root
Standard Library
printf("Input limit:\n"); cout << "Input limit:" << endl;
Sum Numbers
scanf("%d", &n); cin >> n;
Using bool

Summary for (i = 0; i <= n; ++i) for (int i = 0; i <= n; ++i) // Local Decl.
sum = sum + i; sum = sum + i;

printf("Sum of %d", n); cout << "Sum of " << n ;


printf(" numbers is: %d\n", sum); cout << " numbers is: " << sum << endl;

return 0; return 0;
} }

Input limit: Input limit:


10 10
Sum of 10 numbers is: 55 Sum of 10 numbers is: 55

• i must be declared at the beginning (C89) • i declared locally in for loop

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Program 02.05: Using bool

Module 02 C Program C++ Program

Partha Pratim // FileName:bool.c: // FileName:bool.c: // FileName:bool_c++.cpp:


Das #include <stdio.h> #include <stdio.h> #include <iostream>
#define TRUE 1 #include <stdbool.h>
#define FALSE 0 using namespace std;
Objectives &
Outline int main() { int main() { int main() {
Hello World int x = TRUE; bool x = true; bool x = true;
Add numbers
Square Root printf printf cout <<
Standard Library
("bool is %d\n", x); ("bool is %d\n", x); "bool is " << x;
Sum Numbers
Using bool
return 0; return 0; return 0;
Summary } } }

bool is 1 bool is 1 bool is 1

• 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Module Summary

Module 02

Partha Pratim Understanding differences between C and C++ for:


Das
IO
Objectives & Variable declaration
Outline
Hello World
Standard Library
Add numbers
Square Root C++ gives us more flexibility in terms of basic declaration
Standard Library
Sum Numbers and input / output
Using bool

Summary Many C constructs and functions are simplified in C++


which helps to increase the ease of programming

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Module 03

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

Strings Department of Computer Science and Engineering


Indian Institute of Technology, Kharagpur
Summary
[email protected]

Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 03

Partha Pratim Understand array usage in C and C++


Das
Understand vector usage in C++
Objectives &
Outline Understand string functions in C and string type in
Arrays &
Vectors
C++
Fixed Size Array
Arbitrary Size
Array
Vectors

Strings

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 03

Partha Pratim Arrays and Vectors


Das
Fixed size arrays – in C and C++
Objectives & Arbitrary size arrays – in C and C++
Outline
vectors in C++
Arrays &
Vectors Strings in C and C++
Fixed Size Array
Arbitrary Size string functions in C and C++
Array
Vectors string type in C++
Strings String manipulation in C++
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Program 03.01: Fixed Size Array

Module 03 C Program C++ Program

Partha Pratim // File Name:Array_Fixed_Size.c: //FileName:Array_Fixed_Size_c++.cpp:


Das #include <stdio.h> #include <iostream>

int main() { int main() {


Objectives & short age[4]; short age[4];
Outline
age[0] = 23; age[0] = 23;
Arrays &
age[1] = 34; age[1] = 34;
Vectors
age[2] = 65; age[2] = 65;
Fixed Size Array
age[3] = 74; age[3] = 74;
Arbitrary Size
Array
Vectors printf("%d ", age[0]); std::cout << age[0] << " ";
printf("%d ", age[1]); std::cout << age[1] << " ";
Strings printf("%d ", age[2]); std::cout << age[2] << " ";
printf("%d ", age[3]); std::cout << age[3] << " ";
Summary
return 0; return 0;
} }

23 34 65 74 23 34 65 74

• No difference between arrays in C and C++

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Arbitrary Size Array

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Program 03.02: Fixed size large array in C

Module 03 Hard-coded Using manifest constant

Partha Pratim // FileName:Array_Large_Size.c: // FileName:Array_Macro.c:


Das #include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#define MAX 100
Objectives &
Outline int main() { int main() {
int arr[100], sum = 0, i; int arr[MAX], sum = 0, i;
Arrays &
Vectors
printf("Enter no. of elements: "); printf("Enter no. of elements: ");
Fixed Size Array
int count; int count;
Arbitrary Size
Array scanf("%d", &count); scanf("%d", &count);
Vectors
for(i = 0; i < count; i++) { for(i = 0; i < count; i++) {
Strings arr[i] = i; arr[i] = i;
sum + = arr[i]; sum + = arr[i];
Summary } }
printf("Array Sum: %d", sum); printf("Array Sum: %d", sum);

return 0; return 0;
} }

Enter no. of elements: 10 Enter no. of elements: 10


Array Sum: 45 Array Sum: 45

• Hard-coded size • Size by manifest constant

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Program 03.03: Fixed large array / vector

Module 03 C (array & constant) C++ (vector & constant)

Partha Pratim // FileName:Array_Macro.c: // FileName:Array_Macro_c++.cpp:


Das #include <stdio.h> #include <iostream>
#include <stdlib.h> #include <vector>
using namespace std;
Objectives & #define MAX 100 #define MAX 100
Outline
int main() { int main() {
Arrays &
int arr[MAX], sum = 0, i; vector<int> arr(MAX); // Define-time size
Vectors
Fixed Size Array
printf("Enter no. of elements: "); cout <<"Enter the no. of elements: ";
Arbitrary Size
Array int count; int count, j, sum = 0;
Vectors scanf("%d", &count); cin >>count;
for(i = 0; i < count; i++) { for(int i = 0; i < count; i++) {
Strings arr[i] = i; arr[i] = i;
sum + = arr[i]; sum + = arr[i];
Summary } }
printf("Array Sum: %d", sum); cout << "Array Sum: " << sum << endl;
return 0; return 0;
} }

Enter no. of elements: 10 Enter no. of elements: 10


Array Sum: 45 Array Sum: 45

• 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

Module 03 C Program C++ Program

Partha Pratim // FileName:Array_Malloc.c: // FileName:Array_Resize_c++.cpp:


Das #include <stdio.h> #include <iostream>
#include <stdlib.h> #include <vector>
using namespace std;
Objectives &
Outline int main() { int main() {
printf("Enter no. of elements "); cout << "Enter the no. of elements: ";
Arrays &
int count, sum = 0, i; int count, j, sum=0;
Vectors
scanf("%d", &count); cin >> count;
Fixed Size Array
Arbitrary Size
Array int *arr = (int*) malloc vector<int> arr; // Default size
Vectors (sizeof(int)*count); arr.resize(count); // Set resize

Strings for(i = 0; i < count; i++) { for(int i = 0; i < arr.size(); i++) {


arr[i] = i; arr[i] = i;
Summary sum + = arr[i]; sum + = arr[i];
} }
printf("Array Sum:%d ", sum); cout << "Array Sum: " << sum << endl;
return 0; return 0;
} }

Enter no. of elements: 10 Enter no. of elements: 10


Array Sum: 45 Array Sum: 45

• malloc allocates space using sizeof • resize fixes vector size at run-time

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Strings in C and C++

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Program 03.05: Concatenation of Strings

Module 03 C Program C++ Program

Partha Pratim // FileName:Add_strings.c: // FileName:Add_strings_c++.cpp:


Das #include <stdio.h> #include <iostream>
#include <string.h> #include <string>
using namespace std;
Objectives &
Outline int main() { int main(void) {
char str1[] = string str1 = "HELLO ";
Arrays &
{’H’,’E’,’L’,’L’,’O’,’ ’,’\0’};
Vectors
char str2[] = "WORLD"; string str2 = "WORLD";
Fixed Size Array
Arbitrary Size
Array char str[20];
Vectors strcpy(str, str1);
strcat(str, str2); string str = str1 + str2;
Strings
printf("%s\n", str); cout << str;
Summary
return 0; return 0;
} }

HELLO WORLD HELLO WORLD

• Need header string.h • Need header string


• C-String is an array of characters • string is a data-type in C++ standard library
• String concatenation done with strcat function • Strings are concatenated like addition of int
• Need a copy into str
• str must be large to fit the result
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
More on Strings

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Module 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Module 04

Partha Pratim
Das Module 04: Programming in C++
Objectives & Sorting and Searching
Outline

Sorting
Bubble Sort
Standard Library

Searching
Partha Pratim Das
Standard Library

STL: Department of Computer Science and Engineering


algorithm Indian Institute of Technology, Kharagpur
Summary
[email protected]

Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 04

Partha Pratim Implementation of Sorting and Searching in C and C++


Das

Objectives &
Outline

Sorting
Bubble Sort
Standard Library

Searching
Standard Library

STL:
algorithm

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 04

Partha Pratim Sorting in C and C++


Das
Bubble Sort
Objectives & Using Standard Library
Outline
Searching in C and C++
Sorting
Bubble Sort Using Standard Library
Standard Library

Searching algorithm Library


Standard Library

STL:
algorithm

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Program 04.01: Bubble Sort

Module 04 C Program C++ Program

Partha Pratim // FileName:Bubble_Sort.c: // FileName:Bubble_Sort.cpp:


Das #include <stdio.h> #include <iostream>
using namespace std;
int main() { int main() {
Objectives & int data[] = {32, 71, 12, 45, 26}; int data[] = {32, 71, 12, 45, 26};
Outline int i, step, n = 5, temp; int n = 5, temp;
Sorting
for(step = 0; step < n - 1; ++step) for(int step = 0; step < n - 1; ++step)
Bubble Sort
for(i = 0; i < n-step-1; ++i) { for(int i = 0;i < n-step-1; ++i) {
Standard Library
if(data[i] > data[i+1]) { if (data[i] > data[i+1]) {
Searching temp = data[i]; temp = data[i];
Standard Library data[i] = data[i+1]; data[i] = data[i+1];
data[i+1] = temp; data[i+1] = temp;
STL: } }
algorithm } }

Summary for(i = 0; i < n; ++i) for(int i = 0; i < n; ++i)


printf("%d ", data[i]); cout << data[i] << " ";

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.

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Program 04.02: Using sort from standard library

Module 04 C Program (Desc order) C++ Program (Desc order)

Partha Pratim // FileName:qsort.c: // FileName:Algorithm_Cust_c++.cpp:


Das #include <stdio.h> #include <iostream>
#include <stdlib.h> #include <algorithm>
using namespace std;
Objectives &
Outline // compare Function Pointer // compare Function Pointer
int compare(const void *a, const void *b) { bool compare (int i, int j) {
Sorting
return (*(int*)a < *(int*)b); return (i > j);
Bubble Sort
} }
Standard Library

Searching int main () { int main() {


Standard Library int data[] = {32, 71, 12, 45, 26}; int data[] = {32, 71, 12, 45, 26};

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);

Summary for(int i = 0; i < 5; i++) for (int i = 0; i < 5; i++)


printf ("%d ", data[i]); cout << data[i] << " ";

return 0; return 0;
} }

71 45 32 26 12 71 45 32 26 12

• sizeof int, array passed in qsort • Size need not be passed.

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Program 04.03: Using default sort of algorithm

Module 04 C++ Program

Partha Pratim // FileName:Algorithm_Cust_c++.cpp:


Das #include <iostream>
#include <algorithm>
using namespace std;
Objectives &
Outline int main () {
int data[] = {32, 71, 12, 45, 26};
Sorting
Bubble Sort
sort (data, data+5);
Standard Library

Searching for (int i = 0; i < 5; i++)


Standard Library cout << data[i] << " ";

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.

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Program 04.04: Binary Search

Module 04 C Program C++ Program

Partha Pratim // FileName:Binary_Search.c: // FileName:Binary_Search_c++.cpp:


Das #include <stdio.h> #include <iostream>
#include <stdlib.h> #include <algorithm>
using namespace std;
Objectives &
Outline // compare Function Pointer
int compare (const void * a, const void * b) {
Sorting
if ( *(int*)a < *(int*)b ) return -1;
Bubble Sort
if ( *(int*)a == *(int*)b ) return 0;
Standard Library
if ( *(int*)a > *(int*)b ) return 1;
Searching }
Standard Library
int main () { int main() {
STL: int data[] = {1, 2, 3, 4, 5}; int data[] = {1, 2, 3, 4, 5};
algorithm int key = 3; int key = 3;

Summary if (bsearch (&key, data, 5, if (binary_search (data, data+5, key))


sizeof(int), compare))
cout << "found!\n"; cout << "found!\n";
else else
cout << "not found.\n"; cout << "not found.\n";

return 0; return 0;
} }

found! found!

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


The algorithm Library

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Program 04.05: replace and rotate functions

Module 04 Replace Rotate

Partha Pratim // FileName:Replace.cpp: // FileName:Rotate.cpp:


Das #include <iostream> #include <iostream>
#include <algorithm> #include <algorithm>
using namespace std; using namespace std;
Objectives &
Outline int main() { int main() {
int data[] = {1, 2, 3, 4, 5}; int data[] = {1, 2, 3, 4, 5};
Sorting
Bubble Sort
replace (data, data+5, 3, 2); rotate (data, data+2, data+5);
Standard Library

Searching for(int i = 0; i < 5; ++i) for(int i = 0; i < 5; ++i)


Standard Library cout << data[i] << " "; cout << data[i] <<" ";

STL: return 0; return 0;


algorithm } }

Summary
1 2 2 4 5 3 4 5 1 2

• 3rd element replaced with 2 • Array circular shifted around 3rd element.

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Module Summary

Module 04

Partha Pratim Flexibility of defining customised sort algorithms to be


Das
passed as parameter to sort and search functions defined
Objectives &
Outline
in the algorithm library.
Sorting Predefined optimised versions of these sort and search
Bubble Sort
Standard Library functions can also be used.
Searching
Standard Library
There are a number of useful functions like rotate, replace,
STL: merge, swap, remove etc in algorithm library.
algorithm

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Module 05

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 05

Partha Pratim Understanding implementation and use of stack in C


Das
Understanding stack in C++ standard library and its use
Objectives &
Outline

Stack in C
Reverse a String
Eval Postfix

Stack in C++
Reverse a String
Eval Postfix

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 05

Partha Pratim Stack in C


Das
Reverse a String
Objectives & Evaluate a Postfix Expression
Outline
Stack in C++
Stack in C
Reverse a String Reverse a String
Eval Postfix
Evaluate a Postfix Expression
Stack in C++
Reverse a String
Eval Postfix

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Understanding Stack in C

Module 05 Stack is a LIFO (last-In-First-Out) container that can


Partha Pratim
Das
maintain a collection of arbitrary number of data items –
all of the same type
Objectives &
Outline To create a stack in C we need to:
Stack in C Decide on the data type of the elements
Reverse a String
Eval Postfix
Define a structure (container) (with maximum size) for
Stack in C++ stack and declare a top variable in the structure
Reverse a String
Eval Postfix
Write separate functions for push, pop, top, and isempty
Summary
using the declared structure
Note:
Change of the data type of elements, implies
re-implementation for all the stack codes
Change in the structure needs changes in all functions
Unlike sin, sqrt etc. function from C standard library, we
do not have a ready-made stack that we can use
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Common C programs using stack

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

Identification of palindromes (w/ and w/o center-marker)


Conversion of an infix expression to postfix
Depth-first Search (DFS)

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Program 05.01: Reversing a string

Module 05 // FileName: Reverse_String.c void main() {


stack s;
Partha Pratim #include <stdio.h> s.top = -1;
Das
typedef struct stack { char ch, str[10] = "ABCDE";
char data [100];
Objectives & int top; int i, len = sizeof(str);
Outline } stack;
for(i = 0; i < len; i++) {
Stack in C
int empty (stack *p) { push(&s, str[i]);
Reverse a String
return (p->top == -1); }
Eval Postfix
}
Stack in C++ printf ("Reversed String: ");
Reverse a String int top (stack *p) {
Eval Postfix return p -> data [p->top]; while (!empty(&s)){
} printf("%c ", top(&s));
Summary pop(&s);
void push (stack *p, char x) { }
p -> data [++(p -> top)] = x; }
}

void pop (stack *p) {


if (!empty(p)) {
(p->top) = (p->top) -1;
}
}

Reversed String: EDCBA

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Program 05.02: Postfix Expression Evaluation

Module 05 // FileName: PostFix_Evaluation.c void main() {


stack s;
Partha Pratim #include<stdio.h> s.top = -1;
Das
typedef struct stack { // Postfix expression: 1 2 3 * + 4 -
char data [100]; char postfix[] = {’1’,’2’,’3’,’*’,’+’,’4’,’-’};
Objectives & int top;
Outline } stack; int i, op1, op2;
Stack in C
int empty (stack *p) { for(i = 0; i < 7; i++) {
Reverse a String
return (p->top == -1); char ch = postfix[i];
Eval Postfix
} if (isdigit(ch)) push(&s, ch-’0’);
Stack in C++ else {
Reverse a String int top (stack *p) { op2 = top(&s); pop(&s);
Eval Postfix return p -> data [p->top]; op1 = top(&s); pop(&s);
} switch (ch) {
Summary case ’+’:push(&s, op1 + op2);break;
void push (stack *p, char x) { case ’-’:push(&s, op1 - op2);break;
p -> data [++(p -> top)] = x; case ’*’:push(&s, op1 * op2);break;
} case ’/’:push(&s, op1 / op2);break;
}
void pop (stack *p) { }
if (!empty(p)) { }
(p->top) = (p->top) -1; printf("Evaluation %d\n", top(&s));
} }
}

Evaluation 3

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Understanding Stack in C++

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Program 05.03: Reverse a String in C++

Module 05 // FileName: Reverse_String_c++.cpp // FileName: Reverse_String.c


#include<iostream>
Partha Pratim #include<string.h>
Das #include<stack>
using namespace std;
Objectives & int main() { int main() {
Outline char str[10]= "ABCDE"; char str[10] = "ABCDE";
stack<char> s; stack s; s.top = -1;
Stack in C
int i; int i;
Reverse a String
Eval Postfix
for(i = 0; i < strlen(str); i++) for(i = 0; i < strlen(str); i++)
Stack in C++ s.push(str[i]); push(&s, str[i]);
Reverse a String
Eval Postfix cout << "Reversed String: "; printf ("Reversed String: ");

Summary while (!s.empty()) { while (!empty(&s)){


cout << s.top(); printf("%c ", top(&s));
s.pop(); pop(&s);
} }

return 0; return 0;
} }

• No codes for creating stack • Lot of code for creating stack


• No initialization • top to be initialized
• Clean interface for stack functions • Cluttered interface for stack functions
• Available in library – well-tested • Implemented by user – error-prone

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Program 05.04: Postfix Evaluation in C++

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;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Module Summary

Module 05

Partha Pratim C++ standard library provides ready-made stack. It works


Das
like a data type
Objectives &
Outline Any type of element can be used for C++ stack
Stack in C Similar containers as available in C++ standard library
Reverse a String
Eval Postfix include:
Stack in C++ queue
Reverse a String
Eval Postfix deque
Summary list
map
set
... and more

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Module 06

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 06

Partha Pratim Understand const in C++ and contrast with Manifest


Das
Constants
Objectives &
Outline Understand inline in C++ and contrast with Macros
const-ness &
cv-qualifier
const-ness
Advantages
Pointers
volatile

inline
functions
Macros
inline

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 06 const-ness and cv-qualifier


Partha Pratim Notion of const
Das Advantages of const
Objectives &
Natural Constants – π, e
Outline Program Constants – array size
const-ness & Prefer const to #define
cv-qualifier
const-ness
const and pointer
Advantages
Pointers
const-ness of pointer / pointee. How to decide?
volatile
Notion of volatile
inline
functions inline functions
Macros
inline Macros with params
Summary Advantages
Disadvantages
Notion of inline functions
Advantages

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Program 06.01: Manifest constants in C

Module 06 Manifest constants are defined by #define


Partha Pratim
Das
Manifest constants are replaced by CPP (C Pre-Processor)
Source Program Program after CPP
Objectives &
Outline #include <iostream> // Contents of <iostream> header replaced by CPP
#include <cmath> // Contents of <cmath> header replaced by CPP
const-ness & using namespace std; using namespace std;
cv-qualifier
const-ness #define TWO 2 // #define of TWO consumed by CPP
Advantages #define PI 4.0*atan(1.0) // #define of PI consumed by CPP
Pointers
volatile int main() { int main() {
int r = 10; int r = 10;
inline double peri = double peri =
functions TWO * PI * r; 2 * 4.0*atan(1.0) * r; // Replaced by CPP
Macros cout << "Perimeter = " cout << "Perimeter = "
inline << peri << endl; << peri << endl;
Summary return 0; return 0;
} }

Perimeter = 314.159 Perimeter = 314.159

• TWO is a manifest constant • CPP replaces the token TWO by 2


• PI is a manifest constant • CPP replaces the token PI by 4.0*atan(1.0)
• TWO & PI look like variables • Compiler sees them as constants

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Notion of const-ness

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 Using #define Using const

Partha Pratim #include <iostream> #include <iostream>


Das #include <cmath> #include <cmath>
using namespace std; using namespace std;
Objectives & #define TWO 2 const int TWO = 2;
Outline #define PI 4.0*atan(1.0) const double PI = 4.0*atan(1.0);
const-ness &
int main() { int main() {
cv-qualifier
int r = 10; int r = 10;
const-ness double peri = double peri =
Advantages
TWO * PI * r; TWO * PI * r; // No replacement by CPP
Pointers
cout << "Perimeter = " cout << "Perimeter = "
volatile
<< peri << endl; << peri << endl;
inline return 0; return 0;
functions } }
Macros
inline
Perimeter = 314.159 Perimeter = 314.159
Summary

• TWO is a manifest constant • TWO is a const variable initialized to 2


• PI is a manifest constant • PI is a const variable initialized to 4.0*atan(1.0)
• TWO & PI look like variables • TWO & PI are variables
• Types of TWO & PI may be indeterminate • Type of TWO is const int
• Type of PI is const double

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Advantages of 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

Module 06 Prefer const over #define


Partha Pratim Using #define Using const
Das
Manifest Constant Constant Variable
Objectives &
Outline • Is not type safe • Has its type
• Replaced textually by CPP • Visible to the compiler
const-ness & • Cannot be watched in debugger • Can be watched in debugger
cv-qualifier • Evaluated as many times as replaced • Evaluated only on initialization
const-ness
Advantages
Pointers
volatile

inline
functions
Macros
inline

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


const and Pointers

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


const and Pointers: Pointer to Constant data

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


const and Pointers: Constant Pointer

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

Finally, to decide on const-ness, draw a mental line through *


int n = 5;
int * p = &n; // non-const-Pointer to non-const-Pointee
const int * p = &n; // non-const-Pointer to const-Pointee
int * const p = &n; // const-Pointer to non-const-Pointee
const int * const p = &n; // const-Pointer to const-Pointee
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
const and Pointers: The case of C-string

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 Variable Read-Write


Partha Pratim The value of a variable can be read and / or assigned at
Das any point of time
Objectives &
The value assigned to a variable does not change till a
Outline next assignment is made (value is persistent)
const-ness &
cv-qualifier const
const-ness
Advantages
The value of a const variable can be set only at
Pointers
volatile
initialization – cannot be changed afterwards
inline volatile
functions
Macros In contrast, the value of a volatile variable may be
inline
different every time it is read – even if no assignment has
Summary
been made to it
A variable is taken as volatile if it can be changed by
hardware, the kernel, another thread etc.
cv-qualifier: A declaration may be prefixed with a
qualifier – const or volatile
NPTEL MOOCs Programming in C++ Partha Pratim Das 13
Using 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
}

Being volatile, i can be changed by hardware anytime. It waits till


the value becomes 100 (possibly some hardware writes to a port).
NPTEL MOOCs Programming in C++ Partha Pratim Das 14
Program 06.03: Macros with Parameters

Module 06 Macros with Parameters are defined by #define


Partha Pratim
Das
Macros with Parameters are replaced by CPP
Source Program Program after CPP
Objectives &
Outline #include <iostream> // Contents of <iostream> header replaced by CPP
using namespace std; using namespace std;
const-ness &
cv-qualifier #define SQUARE(x) x * x // #define of SQUARE(x) consumed by CPP
const-ness
Advantages int main() { int main() {
Pointers int a = 3, b; int a = 3, b;
volatile
b = SQUARE(a); b = a * a; // Replaced by CPP
inline
functions cout << "Square = " cout << "Square = "
Macros << b << endl; << b << endl;
inline return 0; return 0;
} }
Summary

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Pitfalls of macros

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;

#define SQUARE(x) (x) * (x)


Objectives &
Outline int main() {
int a = 3, b;
const-ness &
cv-qualifier b = SQUARE(++a);
const-ness
Advantages cout << "Square = " << b << endl;
Pointers
volatile return 0;
inline }
functions
Macros Output is 25 in stead of 16 as expected. On the expansion line it gets:
inline

Summary b = (++a) * (++a);

and a is incremented twice before being used! There is no easy fix.

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


inline Function

Module 06

Partha Pratim An inline function is just another functions


Das
The function prototype is preceded by the keyword inline
Objectives &
Outline
An inline function is expanded (inlined) at the site of its call
const-ness &
cv-qualifier and the overhead of passing parameters between caller and
const-ness callee (or called) functions is avoided
Advantages
Pointers
volatile

inline
functions
Macros
inline

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 18


Program 06.04: Macros as inline Functions

Module 06 Define the function


Partha Pratim
Das
Prefix function header with inline
Compile function body and function call together
Objectives &
Outline Using macro Using inline
const-ness & #include <iostream> #include <iostream>
cv-qualifier using namespace std; using namespace std;
const-ness #define SQUARE(x) x * x inline int SQUARE(int x) { return x * x; }
Advantages int main() { int main() {
Pointers int a = 3, b; int a = 3, b;
volatile b = SQUARE(a); b = SQUARE(a);
cout << "Square = " cout << "Square = "
inline
<< b << endl; << b << endl;
functions
return 0; return 0;
Macros
} }
inline

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 19


Macros & inline Functions:
Compare and Contrast
Module 06 Macros inline Functions

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 20


Limitations of Function inlineing

Module 06

Partha Pratim inlineing is a directive – compiler may not inline


Das
functions with large body
Objectives &
Outline inline functions may not be recursive
const-ness &
cv-qualifier
Function body is needed for inlineing at the time of
const-ness function call. Hence, implementation hiding is not
Advantages
Pointers possible. Implement inline functions in header files
volatile

inline inline functions must not have two different definitions


functions
Macros
inline

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 21


Module Summary

Module 06

Partha Pratim Revisit manifest constants from C


Das
Understand const-ness, its use and advantages over
Objectives &
Outline manifest constants
const-ness &
cv-qualifier
Understand the interplay of const and pointer
const-ness
Advantages
Understand the notion and use of volatile data
Pointers
volatile Revisit macros with parameters from C
inline
functions Understand inline functions and their advantages over
Macros
inline
macros
Summary Limitations of inlineing

NPTEL MOOCs Programming in C++ Partha Pratim Das 22


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 23


Module 07

Partha Pratim
Das
Module 07: Programming in C++
Objectives &
Outlines
Reference & Pointer
Reference
variable

Call-by- Partha Pratim Das


reference
Swap in C
Swap in C++ Department of Computer Science and Engineering
const Reference
Parameter Indian Institute of Technology, Kharagpur
Return-by-
reference
[email protected]

I/O of a
Function
Tanwi Mallick
References vs. Srijoni Majumdar
Pointers
Himadri B G S Bhuyan
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 07

Partha Pratim Understand References in C++


Das
Compare and contrast References and Pointers
Objectives &
Outlines

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 07

Partha Pratim Reference variable or Alias


Das
Basic Notion
Objectives & Call-by-reference in C++
Outlines
Example: Swapping two number in C
Reference
variable Using Call-by-value
Call-by- Using Call-by-address
reference
Swap in C
Swap in C++
Call-by-reference in C++ in contrast to Call-by-value in C
const Reference
Parameter Use of const in Alias / Reference
Return-by-
reference Return-by-reference in C++ in contrast to
I/O of a Return-by-value in C
Function

References vs.
Differences between References and Pointers
Pointers

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Reference

Module 07

Partha Pratim A reference is an alias / synonym for an existing variable


Das
int i = 15; // i is a variable
Objectives &
Outlines int &j = i; // j is a reference to i
Reference
variable

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Program 07.01: Behavior of Reference

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

Call-by- ++a; // Changing a appears as change in b


reference cout << "a = " << a << ", b = " << b << endl;
Swap in C
Swap in C++
++b; // Changing b also changes a
const Reference
cout << "a = " << a << ", b = " << b << endl;
Parameter
return 0;
Return-by- }
reference

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Pitfalls in Reference

Module 07 Wrong declaration Reason Correct declaration

Partha Pratim
Das int& i; no variable to refer to – must be initialized int& i = j;

int& j = 5; no address to refer to as 5 is a constant const int& j = 5;


Objectives &
Outlines
int& i = j + k; only temporary address (result of j + k) to refer to const int& i = j + k;
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

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


C++ Program 07.02: Call-by-reference

Module 07 #include <iostream>


using namespace std;
Partha Pratim
Das void Function_under_param_test(// Function prototype
int &b, // Reference parameter
int c); // Value parameter
Objectives &
Outlines int main() {
int a = 20;
Reference
cout << "a = " << a << ", &a = " << &a << endl << endl;
variable
Function_under_param_test(a, a); // Function call
Call-by-
reference return 0;
}
Swap in C
Swap in C++
const Reference
void Function_under_param_test(int &b, int c) { // Function definition
Parameter cout << "b = " << b << ", &b = " << &b << endl << endl;
cout << "c = " << c << ", &c = " << &c << endl << endl;
Return-by- }
reference ------- Output -------
a = 20, &a = 0023FA30
I/O of a
b = 20, &b = 0023FA30
Function
c = 20, &c = 0023F95C
References vs.
Pointers • Param b is call-by-reference while param c is call-by-value
• Actual param a and formal param b get the same value in called function
Summary
• Actual param a and formal param c get the same value in called function
• Actual param a and formal param b get the same value in called function
• However, actual param a and formal param c have different addresses in called function
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
C Program 07.03: Swap in C

Module 07 Call-by-value Call-by-address

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


Das
void swap(int, int); // Call-by-value void swap(int *, int *); // Call-by-address
int main() { int main() {
Objectives & int a = 10, b = 15; int a=10, b=15;
Outlines printf("a= %d & b= %d to swap\n", a, b); printf("a= %d & b= %d to swap\n", a, b);
swap(a, b); swap(&a, &b);
Reference
printf("a= %d & b= %d on swap\n", a, b); printf("a= %d & b= %d on swap\n", a, b);
variable
return 0; return 0;
Call-by- } }
reference
void swap(int c, int d){ void swap(int *x, int *y){
Swap in C
Swap in C++
int t; int t;
const Reference
t = c; t = *x;
Parameter c = d; *x = *y;
d = t; *y = t;
Return-by- } }
reference

I/O of a • a= 10 & b= 15 to swap • a= 10 & b= 15 to swap


Function • a= 10 & b= 15 on swap • a= 15 & b= 10 on swap
References vs.
Pointers • Passing values of a=10 & b=15 • Passing Address of a & b
• In callee; c = 10 & d = 15 • In callee x = Addr(a) & y = Addr(b)
Summary • Swapping the values of c & d • Values at the addresses is swapped
• No change for the values of a & b in caller • Changes for the values of a & b in caller
• Swapping the value of c & d instead of a & b • It is correct, but C++ has a better way out

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Program 07.04: Swap in C & C++

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

Partha Pratim #include <stdio.h> #include <iostream>


Das using namespace std;
void swap(int, int); // Call-by-value void swap(int&, int&); // Call-by-reference
int main() { int main() {
Objectives & int a = 10, b = 15; int a = 10, b = 15;
Outlines printf("a= %d & b= %d to swap\n",a,b); cout<<"a= "<<a<<" & b= "<<b<<"to swap"<<endl;
swap(a, b); swap(a, b);
Reference
printf("a= %d & b= %d on swap\n",a,b); cout<<"a= "<<a<<" & b= "<<b<<"on swap"<<endl;
variable
return 0; return 0;
Call-by- } }
reference
void swap(int c, int d) { void swap(int &x, int &y) {
Swap in C
Swap in C++
int t ; int t ;
const Reference
t = c ; t = x ;
Parameter c = d ; x = y ;
d = t ; y = t ;
Return-by- } }
reference

I/O of a • a= 10 & b= 15 to swap • a= 10 & b= 15 to swap


Function • a= 10 & b= 15 on swap • a= 15 & b= 10 on swap
References vs.
Pointers • Passing values of a=10 & b=15 • Passing values of a = 10 & b = 15
• In callee; c=10 & d=15 • In callee x = 10 & y = 15
Summary • Swapping the values of c & d • Swapping the value x & y
• No change for the values of a & b • Changes the values of a & b
• Here c & d do not share address with a & b • x & y having same address as a & b respectively

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Program 07.05: Reference Parameter as const

Module 07 A reference parameter may get changed in the called


Partha Pratim function
Das
Use const to stop reference parameter being changed
Objectives &
Outlines
const reference – bad const reference – good
Reference
variable #include <iostream> #include <iostream>
using namespace std; using namespace std;
Call-by-
reference int Ref_const(const int &x) { int Ref_const(const int &x) {
Swap in C ++x; // Not allowed
Swap in C++ return (x); return (x + 1);
const Reference } }
Parameter
int main() { int main() {
Return-by-
int a = 10, b; int a = 10, b;
reference
b = Ref_const(a); b = Ref_const(a);
I/O of a cout << "a = " << a <<" and" cout << "a = " << a << " and"
Function << " b = " << b; << " b = " << b;
return 0; return 0;
References vs. } }
Pointers
• Error:Increment of read only Reference ’x’ a = 10 and b = 11
Summary
• Compilation Error: Value of x can’t be changed • No violation.
• Implies, ’a’ can’t be changed through ’x’

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Program 07.06: Return-by-reference

Module 07 A function can return a value by reference


Partha Pratim
Das
C uses Return-by-value
Return-by-value Return-by-reference
Objectives &
Outlines #include <iostream> #include <iostream>
using namespace std; using namespace std;
Reference
variable int Function_Return_By_Val(int &x) { int& Function_Return_By_Ref(int &x) {
cout <<"x = "<<x<<" &x = "<<&x<<endl; cout <<"x = "<<x<<" &x = "<<&x<<endl;
Call-by- return (x); return (x);
reference } }
Swap in C int main() { int main() {
Swap in C++ int a = 10; int a = 10;
const Reference cout <<"a = "<<a<<" &a = "<<&a<<endl; cout <<"a = "<<a<<" &a = "<<&a<<endl;
Parameter

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

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


• Has a different address • Has the same address
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Program 07.07: Return-by-reference can get tricky

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

Partha Pratim #include <iostream> #include <iostream>


Das using namespace std; using namespace std;
int& Return_ref(int &x) { int& Return_ref(int &x) {
int t = x;
Objectives & t++;
Outlines return (x); return (t);
} }
Reference
variable
int main() { int main() {
Call-by- int a = 10, b; int a = 10, b;
reference b = Return_ref(a); b = Return_ref(a);
cout << "a = " << a << " and b = " cout << "a = " << a << " and b = "
Swap in C
Swap in C++
<< b << endl; << b << endl;
const Reference
Parameter Return_ref(a) = 3; // Changes Return_ref(a) = 3;
// reference
Return-by- cout << "a = " << a; cout << "a = " << a;
reference
return 0; return 0;
I/O of a
} }
Function
a = 10 and b = 10 a = 10 and b = 11
References vs.
a=3 a = 10
Pointers

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


I/O of a Function

Module 07 In C++ we can changes values with a function as follows:


Partha Pratim
Das
Orifice Purpose Mechanism
Value Parameter Input Call-by-value
Objectives &
Outlines Reference Parameter In-Out Call-by-reference
Reference const Reference Parameter Input Call-by-reference
variable

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Recommended Mechanisms

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Difference between Reference and Pointer

Module 07 Pointers References


Partha Pratim • Refers to an address • Refers to an address
Das • Pointers can point to NULL. • References cannot be NULL
int *p = NULL; // p is not pointing int &j ; //wrong
Objectives & • Pointers can point to different vari- • For a reference, its referent is fixed
Outlines
ables at different times
Reference int a, c, &b = a; // Okay
variable
int a, b, *p; ........
Call-by- p = &a; // p points to a &b = c // Error
reference ...
Swap in C
Swap in C++
p = &b // p points to b
const Reference
Parameter
• NULL checking is required • Makes code faster
Return-by-
reference
Does not require NULL checking
• Allows users to operate on the ad- • Does not allow users to operate
I/O of a
Function
dress – diff pointers, increment, etc. on the address. All operations are
interpreted for the referent
References vs. • Array of pointers can be defined • Array of references not allowed
Pointers

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Module Summary

Module 07

Partha Pratim Introduced reference in C++


Das
Studied the difference between call-by-value and
Objectives &
Outlines call-by-reference
Reference
variable
Studied the difference between return-by-value and
Call-by-
return-by-reference
reference
Swap in C
Discussed the difference between References and Pointers
Swap in C++
const Reference
Parameter

Return-by-
reference

I/O of a
Function

References vs.
Pointers

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 16


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Module 08

Partha Pratim
Das Module 08: Programming C++
Objectives & Default Parameters & Function Overloading
Outline

Default
Parameter

Function Partha Pratim Das


Overloading

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 08

Partha Pratim Understand default parameters


Das
Understand function overloading and Resolution
Objectives &
Outline

Default
Parameter

Function
Overloading

Overload
Resolution

Default
Parameters in
Overloading

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 08

Partha Pratim Default parameter


Das
Motivation
Objectives & Call function with default parameter
Outline
Highlighted Points
Default
Parameter
Restrictions
Function Function overloading
Overloading
Meaning & Motivation
Overload
Resolution Necessity of function overloading in Contrast with C
Default Static Polymorphism
Parameters in
Overloading Meaning
Summary Overloading function
Overload Resolution
Default parameters and Function Overloading

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Motivation: Example CreateWindow in MSDN

Module 08 Declaration of CreateWindow Calling CreateWindow

Partha Pratim HWND WINAPI CreateWindow( hWnd = CreateWindow(


Das _In_opt_ LPCTSTR lpClassName, ClsName,
_In_opt_ LPCTSTR lpWindowName, WndName,
_In_ DWORD dwStyle, WS_OVERLAPPEDWINDOW,
Objectives & _In_ int x, CW_USEDEFAULT,
Outline _In_ int y, CW_USEDEFAULT,
_In_ int nWidth, CW_USEDEFAULT,
Default
_In_ int nHeight, CW_USEDEFAULT,
Parameter
_In_opt_ HWND hWndParent, NULL,
Function _In_opt_ HMENU hMenu, NULL,
Overloading _In_opt_ HINSTANCE hInstance, hInstance,
_In_opt_ LPVOID lpParam NULL
Overload ); );
Resolution

Default There are 11 Number of parameters in CreateWindow()


Parameters in
Overloading Out of these 11, 7 parameters (4 are CWUSEDEFAULT and 3 are NULL) usually
Summary get fixed values in a call
Instead of using these 7 fixed valued Parameters at the time of calling, we
could have avoided those by assigning those value much earlier in function
formal parameter

C++ allows us to do so through the mechanism called Default parameters


NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Program 08.01: Function with a default parameter

Module 08

Partha Pratim #include <iostream>


Das
using namespace std;
Objectives &
Outline int IdentityFunction(int a = 10) { // Default value for the parameter
return (a);
Default
Parameter }
Function
Overloading
int main() {
int x = 5, y;
Overload
Resolution
y = IdentityFunction(x); // Usual function call
Default cout << "y = " << y << endl;
Parameters in
Overloading
y = IdentityFunction(); // Uses default parameter
Summary
cout << "y = " << y << endl;
}
----------
y = 5
y = 10

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Program 08.02: Function with 2 default parameters

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

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


cout << "Sum = " << z << endl;
}
----------
Sum = 11
Sum = 25
Sum = 30
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Default Parameter: Highlighted Points

Module 08

Partha Pratim C++ allows programmer to assign default values to the


Das
function parameters
Objectives &
Outline Default values are specified while prototyping the function
Default
Parameter
Default parameters are required while calling functions
Function
with fewer arguments or without any argument
Overloading
Better to use default value for less used parameters
Overload
Resolution Default arguments may be expressions also
Default
Parameters in
Overloading

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Restrictions on default parameters

Module 08 All parameters to the right of a parameter with default


Partha Pratim argument must have default arguments (function f)
Das
Default arguments cannot be re-defined (function g)
Objectives &
Outline All non-defaulted parameters needed in a call (call g())
#include <iostream>
Default
Parameter void f(int, double = 0.0, char *);
Function // Error C2548: ’f’: missing default parameter for parameter 3
Overloading
void g(int, double = 0, char * = NULL); // OK
Overload void g(int, double = 1, char * = NULL);
Resolution // Error C2572: ’g’: redefinition of default parameter : parameter 3
// Error C2572: ’g’: redefinition of default parameter : parameter 2
Default
Parameters in int main() {
Overloading int i = 5; double d = 1.2; char c = ’b’;

Summary g(); // Error C2660: ’g’: function does not take 0 arguments
g(i);
g(i, d);
g(i, d, &c);
return 0;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Restrictions on default parameters

Module 08 Default parameters should be supplied only in a header file


Partha Pratim
and not in the definition of a function
// Header file: myFunc.h
Das
void g(int, double, char = ’a’);
----------------------------------------------------
Objectives & // Source File: myFunc.cpp
Outline #include <iostream>
using namespace std;
Default #include "myFunc.h"
Parameter
void g(int i, double d, char c) {
Function cout << i << ’ ’ << d << ’ ’ << c << endl;
Overloading }
----------------------------------------------------
Overload
// Application File: Apps.cpp
Resolution
#include <iostream>
Default #include "myFunc.h"
Parameters in // void g(int, double, char = ’a’);
Overloading
void g(int i, double f = 0.0, char ch); // OK a new overload
Summary void g(int i = 0, double f, char ch); // OK a new overload
int main() {
int i = 5; double d = 1.2; char c = ’b’;

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

Objectives & void Multiply_M_M (Mat a, Mat b, Mat* c) { /* c = a * b */ }


Outline void Multiply_M_VC (Mat a, VecCol b, VecCol* c) { /* c = a * b */ }
void Multiply_VR_M (VecRow a, Mat b, VecRow* c) { /* c = a * b */ }
Default void Multiply_VC_VR(VecCol a, VecRow b, Mat* c) { /* c = a * b */ }
Parameter void Multiply_VR_VC(VecRow a, VecCol b, int* c) { /* c = a * b */ }

Function int main() {


Overloading Mat m1, m2, rm; VecRow rv, rrv; VecCol cv, rcv; int r;
Multiply_M_M (m1, m2, &rm); // rm <-- m1 * m2
Overload Multiply_M_VC (m1, cv, &rcv); // rcv <-- m1 * cv
Resolution Multiply_VR_M (rv, m2, &rrv); // rrv <-- rv * m2
Multiply_VC_VR(cv, rv, &rm); // rm <-- cv * rv
Default
Multiply_VR_VC(rv, cv, &r); // r <-- rv * cv
Parameters in
return 0;
Overloading
}
Summary
5 multiplication functions share same functionality but different
argument types
C treats them as 5 separate functions
C++ has an elegant solution
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Function overloads: Matrix Multiplication in C++

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;
}

These 5 functions having different argument types are treated


as one function (Multiply) in C++
This is called Function Overloading or Static Polymorphism
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Program 08.03/04: Function Overloading

Module 08 Define multiple functions having the same name


Partha Pratim
Das
Binding happens at compile time
Same # of Parameters Different # of Parameters
Objectives &
Outline #include <iostream> #include <iostream>
using namespace std; using namespace std;
Default int Add(int a, int b) { return (a + b); } int Area(int a, int b) { return (a * b); }
Parameter double Add(double c, double d) { int Area(int c) {
return (c + d); return (c * c);
Function } }
Overloading int main() { int main(){
int x = 5, y = 6, z; int x = 10, y = 12, z = 5, t;
Overload z = Add(x, y); t = Area(x, y);
Resolution // int Add(int, int) // int Add(int, int)
cout << "int sum = " << z; cout << "Area of Rectangle = " << t;
Default
Parameters in double s = 3.5, t = 4.25, u; int z = 5, u;
Overloading u = Add(s, t); u = Area(z);
// double Add(double, double) // int Add(int)
Summary
cout << "double sum = " << u << endl; cout << " Area of Square = " << u << endl;

return 0; return 0;
} }

int sum = 11 double sum = 7.75 Area of Rectangle = 12 Area of Square = 25


• Same Add function • Same Area function
• Same # of parameters but different types • Different # of parameters

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Program 08.05: Restrictions in Function
Overloading
Module 08 Two functions having the same signature but different return
Partha Pratim types cannot be overloaded
Das
#include <iostream>
Objectives & using namespace std;
Outline
int Area(int a, int b) { return (a * b); }
Default double Area(int a, int b) { return (a * b); }
Parameter // Error C2556: ’double Area(int,int)’: overloaded function differs only by return type
// from ’int Area(int,int)’
Function // Error C2371: ’Area’: redefinition; different basic types
Overloading
int main() {
Overload
int x = 10, y = 12, z = 5, t;
Resolution
double f;
Default
Parameters in t = Area(x, y);
Overloading // Error C2568: ’=’: unable to resolve function overload
// Error C3861: ’Area’: identifier not found
Summary
cout << "Multiplication = " << t << endl;

f = Area(y, z); // Errors C2568 and C3861 as above


cout << "Multiplication = " << f << endl;

return 0;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Function Overloading – Summary of Rules

Module 08 The same function name may be used in several definitions


Partha Pratim
Das Functions with the same name must have different number of
formal parameters and/or different types of formal parameters
Objectives &
Outline Function selection is based on the number and the types of the
Default
Parameter
actual parameters at the places of invocation
Function Function selection (Overload Resolution) is performed by the
Overloading
compiler
Overload
Resolution
Two functions having the same signature but different return
Default
Parameters in
types will result in a compilation error due to attempt to
Overloading re-declare
Summary
Overloading allows Static Polymorphism

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Overload Resolution

Module 08

Partha Pratim To resolve overloaded functions with one parameter


Das
Identify the set of Candidate Functions
Objectives & From the set of candidate functions identify the set of
Outline
Viable Functions
Default
Parameter
Select the Best viable function through (Order is
important)
Function
Overloading Exact Match
Overload Promotion
Resolution Standard type conversion
Default User defined type conversion
Parameters in
Overloading

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Overload Resolution: Exact Match

Module 08

Partha Pratim lvalue-to-rvalue conversion


Das
Most common
Objectives &
Outline
Array-to-pointer conversion
Default
Definitions: int ar[10];
Parameter
void f(int *a);
Function
Overloading Call: f(ar)
Overload Function-to-pointer conversion
Resolution
Definitions: typedef int (*fp) (int);
Default
Parameters in void f(int, fp);
Overloading
int g(int);
Summary
Call: f(5, g)
Qualification conversion
Converting pointer (only) to const pointer

NPTEL MOOCs Programming in C++ Partha Pratim Das 16


Overload Resolution: Promotion & Conversion

Module 08

Partha Pratim Examples of Promotion


Das
char to int; float to double
Objectives & enum to int / short / unsigned int / ...
Outline
bool to int
Default
Parameter Examples of Standard Conversion
Function integral conversion
Overloading
floating point conversion
Overload
Resolution floating point to integral conversion
Default The above 3 may be dangerous!
Parameters in
Overloading
pointer conversion
bool conversion
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Example: Overload Resolution with one parameter

Module 08 In the context of a list of function prototypes:


Partha Pratim int g(double); // F1
Das
void f(); // F2
Objectives &
void f(int); // F3
Outline double h(void); // F4
Default
int g(char, int); // F5
Parameter void f(double, double = 3.4); // F6
void h(int, double); // F7
Function
Overloading void f(char, char *); // F8
Overload
Resolution
The call site to resolve is:
Default f(5.6);
Parameters in
Overloading

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 18


Example: Overload Resolution fails

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

Default int main() {


Parameter
float p = 4.5, t = 10.5;
Function int s = 30;
Overloading

Overload fun(p, s); // CALL - 1


Resolution fun(t); // CALL - 2
Default return 0;
Parameters in }
Overloading

Summary
• CALL - 1: Matches Function 2 & Function 3
• CALL - 2: Matches Function 1 & Function 3
• Results in ambiguity

NPTEL MOOCs Programming in C++ Partha Pratim Das 19


Program 08.06/07:
Default Parameter & Function Overload
Module 08 Compilers deal with default parameters as a special case of
Partha Pratim function overloading
Das
Default Parameters Function Overload
Objectives & #include <iostream> #include <iostream>
Outline using namespace std; using namespace std;
int f(int a = 1, int b = 2); int f();
Default int f(int);
Parameter int f(int, int);
Function
int main() { int main() {
Overloading
int x = 5, y = 6; int x = 5, y = 6;
Overload
Resolution f(); // a = 1, b = 2 f(); // int f();
f(x); // a = x = 5, b = 2 f(x); // int f(int);
Default f(x, y); // a = x = 5, b = y = 6 f(x, y); // int f(int, int);
Parameters in
Overloading return 0; return 0;
} }
Summary
• Function f has 2 parameters overloaded • Function f is overloaded with up to 3 parameters
• f can have 3 possible forms of call • f can have 3 possible forms of call
• No overload here use default parameters

NPTEL MOOCs Programming in C++ Partha Pratim Das 20


Program 08.08:
Default Parameter & Function Overload
Module 08 Function overloading can use default parameter
Partha Pratim However, with default parameters, the overloaded functions
Das
should still be resolvable
Objectives & #include<iostream>
Outline
using namespace std;
Default
Parameter
int Area(int a, int b = 10) { return (a * b); }
Function double Area(double c, double d) { return (c * d); }
Overloading

Overload int main() {


Resolution int x = 10, y = 12, t;
Default double z = 20.5, u = 5.0, f;
Parameters in
Overloading
t = Area(x); // Binds int Area(int, int = 10)
Summary cout << "Area = " << t << endl; // t = 100

f = Area(z, y); // Binds double Area(double, double)


cout << "Area = " << f << endl; // f = 102.5

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

Function int main() {


Overloading int x = 5, y = 6;
Overload
Resolution f(); // Error C2668: ’f’: ambiguous call to overloaded function
Default
// More than one instance of overloaded function "f"
Parameters in // matches the argument list:
Overloading // function "f()"
Summary // function "f(int = 0)"

f(x); // int f(int);


f(x, y); // int f(int, int);

return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 22
Module Summary

Module 08

Partha Pratim Introduced the notion of Default parameters and discussed


Das
several examples
Objectives &
Outline Identified the necessity of function overloading
Default
Parameter
Introduced static Polymorphism and discussed examples
Function
and restrictions
Overloading
Discussed an outline for Overload resolution
Overload
Resolution Discussed the mix of default Parameters and function
Default
Parameters in
overloading
Overloading

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 23


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 24


Module 09

Partha Pratim
Das Module 09: Programming in C++
Objectives & Operator Overloading
Outline

Operators &
Functions

Operator Partha Pratim Das


Overloading

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 09

Partha Pratim Understand the Operator Overloading


Das

Objectives &
Outline

Operators &
Functions

Operator
Overloading

Examples
String
Enum

Operator
Overloading
Rules

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 09

Partha Pratim Basic Differences between Operators & Functions


Das
Operator Overloading
Objectives &
Outline Examples of Operator Overloading
Operators & operator+ for String & Enum
Functions

Operator Operator Overloading Rules


Overloading

Examples
String
Enum

Operator
Overloading
Rules

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Operator & Function

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


Partha Pratim
Das unsigned int Multiply(unsigned x, unsigned y) {
int prod = 0;
Objectives & while (y-- > 0) prod += x;
Outline
return prod;
Operators & }
Functions

Operator int main() {


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

return 0;
}

Same computation by an operator and a function


NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Difference between Operator & Functions

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Operator Functions in C++

Module 09 Introduces a new keyword: operator


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

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

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


NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Program 09.01: String Concatenation

Module 09 Concatenation by string functions Concatenation operator

Partha Pratim #include <iostream> #include <iostream>


Das #include <cstring> #include <cstring>
using namespace std; using namespace std;
typedef struct _String { char *str; typedef struct _String { char *str; } String;
Objectives & } String; String operator+(const String& s1, const String& s2)
Outline int main(){ String s;
String fName, lName, name; s.str = (char *) malloc(strlen(s1.str) +
Operators &
fName.str = strdup("Partha "); strlen(s2.str) + 1);
Functions
lName.str = strdup("Das" ); strcpy(s.str, s1.str);
Operator name.str = (char *) malloc( strcat(s.str, s2.str);
Overloading strlen(fName.str) + return s;
strlen(lName.str) + 1); }
Examples strcpy(name.str, fName.str); int main() {
String strcat(name.str, lName.str); String fName, lName, name;
Enum fName.str = strdup("Partha ");
cout << "First Name: " << lName.str = strdup("Das");
Operator fName.str << endl;
Overloading cout << "Last Name: " << name = fName + lName; // Overload operator +
Rules lName.str << endl;
cout << "Full Name: " << cout << "First Name: " << fName.str << endl;
Summary name.str << endl; cout << "Last Name: " << lName.str << endl;
return 0; cout << "Full Name: " << name.str << endl;
} return 0;
---------- }
First Name: Partha ----------
Last Name: Das First Name: Partha
Full Name: Partha Das Last Name: Das
Full Name: Partha Das
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Program 09.02: A new semantics for operator+
w/o Overloading + Overloading operator +
Module 09
#include <iostream> #include <iostream>
Partha Pratim using namespace std; using namespace std;
Das enum E {C0 = 0, C1 = 1, C2 = 2}; enum E {C0 = 0, C1 = 1, C2 = 2};

E operator+(const E& a, const E& b) {


Objectives &
unsigned int uia = a, uib = b;
Outline
unsigned int t = (uia + uib) % 3;
Operators & return (E) t;
Functions }
int main() { int main() {
Operator E a = C1, b = C2; E a = C1, b = C2;
Overloading int x = -1; int x = -1;

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Operator Overloading – Summary of Rules

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Overloading disallowed for

Module 09 Operator Reason


Partha Pratim
Das • dot (.) • It will raise question whether it is for object refer-
ence or overloading
Objectives &
Outline
• Scope Resolution ( :: ) • It performs a (compile time) scope resolution rather
Operators & than an expression evaluation.
Functions

Operator • Ternary (? :) • overloading expr1 ? expr2 : expr3 would not be


Overloading
able to guarantee that only one of expr2 and expr3
Examples was executed
String
Enum
• sizeof • Sizeof cannot be overloaded because built-in oper-
Operator ations, such as incrementing a pointer into an array
Overloading
Rules implicitly depends on it
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Do not overload these operators

Module 09 Operator Reason


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

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Module Summary

Module 09

Partha Pratim Introduced operator overloading


Das
Explained the rules of operator overloading
Objectives &
Outline

Operators &
Functions

Operator
Overloading

Examples
String
Enum

Operator
Overloading
Rules

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Module 10

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 10

Partha Pratim Understand the dynamic memory management in C++


Das

Objectives &
Outline

Memory
Management
in C
malloc & free

Memory
Management
in C++
new & delete
Array
Placement new
Restrictions

Overloading
new & delete

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 10

Partha Pratim Memory management in C


Das
malloc() & free()
Objectives &
Outline
Memory management in C++
Memory
new and delete
Management Array new[] and delete[]
in C
malloc & free Placement new()
Memory Restrictions
Management
in C++ Overloading new and delete
new & delete
Array
Placement new
Restrictions

Overloading
new & delete

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Program 10.01/02: malloc() & free():
C & C++
C Program C++ Program
Module 10
#include <stdio.h> #include <iostream>
Partha Pratim #include <stdlib.h> #include <cstdlib>
Das using namespace std;

int main() { int main() {


Objectives & int *p = (int *)malloc(sizeof(int)); int *p = (int *)malloc(sizeof(int));
Outline *p = 5; *p = 5;

Memory printf("%d", *p); cout << *p;


Management
in C free(p); free(p);
malloc & free
return 0; return 0;
Memory
} }
Management
----- -----
in C++
5 5
new & delete
Array Dynamic memory management functions in stdlib.h header for C
Placement new (cstdlib header for C++)
Restrictions

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Program 10.02/03: operator new & delete:
Dynamic memory management in C++
Module 10 C++ introduces operators new and delete to dynamically allocate and
Partha Pratim
de-allocate memory:
Das malloc() & free() Operatorsnew & delete

Objectives & #include <iostream> #include <iostream>


Outline #include <cstdlib>
using namespace std; using namespace std;
Memory
Management int main() { int main() {
in C int *p = (int *)malloc(sizeof(int)); int *p = new int(5);
malloc & free *p = 5;

Memory cout << *p; cout << *p;


Management
in C++ free(p); delete p;
new & delete
Array return 0; return 0;
Placement new } }
Restrictions ----- -----
5 5
Overloading
new & delete • Function malloc() for allocation on heap • Operator new for allocation on heap
• sizeof(int) needs to be provided • No size specification needed, type suffices
Summary
• Allocated memory returned as void * • Allocated memory returned as int *
• Casting to int * needed • No casting needed
• Cannot be initialized • Can be initialized
• Function free() for de-allocation from heap • Operator delete for de-allocation from heap
• Library feature – header cstdlib needed • Core language feature – no header needed

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Program 10.02/04: Functions:
operator new() & operator delete()
Module 10 C++ also allows operator new and operator delete functions to
Partha Pratim
dynamically allocate and de-allocate memory:
Das malloc() & free() new & delete

Objectives & #include <iostream> #include <iostream>


Outline #include <cstdlib> #include <cstdlib>
using namespace std; using namespace std;
Memory
Management int main() { int main(){
in C int *p = (int *)malloc(sizeof(int)); int *p = (int *)operator new(sizeof(int));
malloc & free *p = 5; *p = 5;

Memory cout << *p; cout << *p;


Management
in C++ free(p); operator delete(p);
new & delete
Array return 0; return 0;
Placement new } }
Restrictions ----- -----
5 5
Overloading
new & delete • Function malloc() for allocation on heap • Function operator new() for allocation on
heap
Summary
• Function free() for de-allocation from heap • Function operator delete() for de-allocation
from heap

There is a major difference between operator new and function operator new(). We explore this
angle more after we learn about classes

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


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

Partha Pratim #include <iostream> #include <iostream>


Das #include <cstdlib> using namespace std;
using namespace std;
Objectives & int main() { int main() {
Outline int *a = (int *)malloc(sizeof(int)* 3); int *a = new int[3];
a[0] = 10; a[1] = 20; a[2] = 30; a[0] = 10; a[1] = 20; a[2] = 30;
Memory
Management
for (int i = 0; i < 3; ++i) for (int i = 0; i < 3; ++i)
in C
cout << "a[" << i << "] = " cout << "a[" << i << "] = "
malloc & free << a[i] << " "; << a[i] << " ";
Memory cout << endl; cout << endl;
Management
in C++ free(a); delete [] a;
new & delete
Array
return 0; return 0;
Placement new } }
Restrictions ----- -----
a[0] = 10 a[1] = 20 a[2] = 30 a[0] = 10 a[1] = 20 a[2] = 30
Overloading
new & delete • Allocation by malloc() on heap • Allocation by operator new[] (different from
operator new) on heap
Summary • # of elements implicit in size passed to malloc() • # of elements explicitly passed to operator
new[]
• Release by free() from heap • Release by operator delete[] (different
from operator delete) from heap

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Program 10.07: Operator new():
Placement new in C++
#include <iostream> using namespace std;
Module 10 int main() {
unsigned char buf[sizeof(int)* 2]; // Buffer on stack
Partha Pratim
Das // placement new in buffer buf
int *pInt = new (buf) int (3); int *qInt = new (buf+sizeof(int)) int (5);
Objectives &
int *pBuf = (int *)(buf + 0); int *qBuf = (int *)(buf + sizeof(int));
Outline
cout << "Buf Addr Int Addr" << endl;
Memory cout << pBuf << " " << pInt << endl << qBuf << " " << qInt << endl;
Management cout << "1st Int 2nd Int" << endl;
in C cout << *pBuf << " " << *qBuf << endl;
malloc & free
int *rInt = new int(7); // heap allocation
Memory cout << "Heap Addr 3rd Int" << endl;
Management cout << rInt << " " << *rInt << endl;
in C++ delete rInt; // delete integer from heap
new & delete
Array // No delete for placement new
Placement new
Restrictions return 0;
}
Overloading -----
new & delete Buf Addr Int Addr • Placement new operator takes a buffer address to place objects
001BFC50 001BFC50 • These are not dynamically allocated on heap –
Summary may be allocated on stack
001BFC54 001BFC54
1st Int 2nd Int • Allocations by Placement new operator must not be deleted
3 5
Heap Addr 3rd Int
003799B8 7

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Mixing malloc, operator new, etc

Module 10 Allocation and De-Allocation must correctly match. Do not free


Partha Pratim
the space created by new using free(). And do not use
Das delete if memory is allocated through malloc(). These may
Objectives &
results in memory corruption
Outline

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;

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


Outline cout << "Overloaded new" << endl;
void *ptr;
Memory ptr = malloc(n); // Memory allocated to ptr
Management return ptr;
in C }
malloc & free void operator delete(void *p) { // definition of delete
cout << "Overloaded delete" << endl;
Memory free(p); // Allocated memory released
Management }
in C++ int main() {
new & delete int *p = new int; // calling overloaded operator new
Array *p = 30; // Assign value to the location
Placement new cout << "The value is :\t" << *p << endl;
Restrictions delete p; // calling overloaded operator delete
return 0;
Overloading
new & delete
} • operator new overloaded
----- • The first parameter of overloaded operator new must be size t
Summary Overloaded new • The return type of overloaded operator new must be void *
The value is : 30 • The first parameter of overloaded operator delete must be void *
Overloaded delete • The return type of overloaded operator delete must be void
• More parameters may be used for overloading
• operator delete should not be overloaded (usually) with extra parameters

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Program 10.09: Overloading operator new[]

Module 10 #include <iostream>


#include <cstdlib>
Partha Pratim using namespace std;
Das
void* operator new [] (size_t os, char setv) { // Fill the allocated array with setv
void *t = operator new(os);
Objectives & memset(t, setv, os);
Outline return t;
}
Memory
Management void operator delete[] (void *ss) {
in C operator delete(ss);
malloc & free }
Memory
Management int main() {
in C++ char *t = new(’#’)char[10]; // Allocate array of 10 elements and fill with ’#’
new & delete
cout << "p = " << (int) (t) << endl;
Array
Placement new
for (int k = 0; k < 10; ++k)
Restrictions cout << t[k];

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Module Summary

Module 10

Partha Pratim Introduced new and delete for dynamic memory


Das
management in C++
Objectives &
Outline Understood the difference between new, new[] and
Memory delete, delete[]
Management
in C Compared memory management in C with C++
malloc & free

Memory Explored the overloading of new, new[] and delete,


Management
in C++ delete[] operators
new & delete
Array
Placement new
Restrictions

Overloading
new & delete

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Module 11

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

this pointer Tanwi Mallick


Srijoni Majumdar
State of an
Object Himadri B G S Bhuyan
Complex
Rectangle
Stack

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 11

Partha Pratim Understand the concept of classes and objects in C++


Das

Objectives &
Outline

Classes

Objects

Data Members
Complex
Rectangle
Stack

Member
Functions
Complex
Rectangle
Stack

this pointer

State of an
Object
Complex
Rectangle
Stack

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 11

Partha Pratim Classes


Das
Objects
Objectives &
Outline Data Members of a class
Classes
Member functions of a class
Objects

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Classes

Module 11 A class is an implementation of a type. It is the only way to


Partha Pratim implement User-defined Data Type (UDT)
Das
A class contains data members / attributes
Objectives &
Outline A class has operations / member functions / methods
Classes
A class defines a namespace
Objects

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

Module 11 An object of a class is an instance created according to its


Partha Pratim blue print. Objects can be automatically, statically, or
Das
dynamically created
Objectives &
Outline
A object comprises data members that specify its state
Classes A object supports member functions that specify its behavior
Objects
Data members of an object can be accesses by ”.” (dot)
Data Members
Complex operator on the object
Rectangle
Stack
Member functions are invoked by ”.” (dot) operator on the
Member
Functions object
Complex
Rectangle An implicit this pointer holds the address of an object. This
Stack
serves the identity of the object in C++
this pointer

State of an this pointer is implicitly passed to methods


Object
Complex
Rectangle
Stack

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Program 11.01/02: Complex Numbers:
Attributes
Module 11 C Program C++ Program

Partha Pratim // File Name:Complex_object.c: // File Name:Complex_object_c++.cpp:


Das #include <stdio.h> #include <iostream>
using namespace std;
Objectives & typedef struct Complex { // struct class Complex { public: // class
Outline double re, im; // Data members double re, im; // Data members
} Complex; };
Classes

Objects int main() { int main() {


// Variable n1 declared, initialized // Object n1 declared, initialized
Data Members Complex n1 = {4.2, 5.3}; Complex n1 = {4.2, 5.3};
Complex printf("%d %d", n1.re, n1.im); // Use cout << n1.re << " " << n1.im; // Use
Rectangle return 0; return 0;
Stack } }
----- -----
Member 4.2 5.3 4.2 5.3
Functions
Complex
Rectangle • struct is a keyword in C for data aggregation • class is a new keyword in C+ for data aggre-
Stack gation
• The struct Complex is defined as composite • The class Complex is defined as composite
this pointer data type containing two double (re, im) data data type containing two double (re, im) data
members members
State of an
• struct Complex is a derived data type used to • class Complex is User-defined Data Type
Object
create Complex type variable n1 (UDT) used to create Complex type object n1
Complex
• Data members are accessed using ’.’ operator • Data members are accessed using ’.’ operator.
Rectangle
• struct only aggregates • class aggregates and helps to do more for
Stack
building a UDT
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Program 11.03/04: Points and Rectangles:
Attributes
C Program C++ Program
Module 11
// File Name:Rectangle_object.c: // File Name:Rectangle_object_c++.cpp:
Partha Pratim #include <stdio.h> #include <iostream>
Das using namespace std;

typedef struct { // struct Point class Point { public: // class Point


Objectives &
int x; int y; int x; int y; // Data members
Outline
} Point; };
Classes
typedef struct { // Rect uses Point class Rect { public: // Rect uses Point
Objects Point TL; // Top-Left Point TL; // Top-Left
Point BR; // Bottom-Right Point BR; // Bottom-Right
Data Members } Rect; };
Complex
Rectangle int main() { int main() {
Stack Rect r = {{0,2}, {5,7}}; Rect r = {{0,2}, {5,7}};
// r.TL <-- {0,2}; r.BR <-- {5,7} // r.TL <-- {0,2}; r.BR <-- {5,7}
Member
// r.TL.x <-- 0; r.TL.y <-- 2 // r.TL.x <-- 0; r.TL.y <-- 2
Functions
Complex // Members of structure r accessed // Rectangle Object r accessed
Rectangle
printf("[(%d %d) (%d %d)]", cout << "[(" << r.TL.x << " " << r.TL.y <<
Stack
r.TL.x, r.TL.y, r.BR.x, r.BR.y); ") (" << r.BR.x << " " << r.BR.y << ")]";
this pointer return 0; return 0;
} }
State of an ----- -----
Object [(0 2) (5 7)] [(0 2) (5 7)]
Complex
Rectangle
Stack • Data members of user-defined data types

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Program 11.05/06: Stacks:
Attributes
Module 11 C Program C++ Program

Partha Pratim // File Name:Stack_object.c: // File Name:Stack_object_c++.cpp:


Das #include <stdio.h> #include <iostream>
using namespace std;
Objectives & typedef struct Stack { // struct Stack class Stack { public: // class Stack
Outline char data [100]; char data [100];
int top; int top;
Classes
} Stack; };
Objects
// Codes for push, pop, top, empty // Codes for push, pop, top, empty
Data Members
Complex int main() { int main() {
Rectangle // Variable s declared // Object s declared
Stack Stack s; Stack s;
s.top = -1; s.top = -1;
Member
Functions // Using stack for solving problems // Using stack for solving problems
Complex
Rectangle return 0; return 0;
Stack } }
this pointer

State of an • Data members of mixed data types


Object
Complex
Rectangle
Stack

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Classes

Module 11 A class is an implementation of a type. It is the only way to


Partha Pratim implement User-defined Data Type (UDT)
Das
A class contains data members / attributes.
Objectives &
Outline A class defines a namespace
Classes

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

Member A class is a blue print for its instances (objects)


Functions
Complex
Rectangle
Stack

this pointer

State of an
Object
Complex
Rectangle
Stack

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Objects

Module 11 An object of a class is an instance created according to its


Partha Pratim blue print. Objects can be automatically, statically, or
Das
dynamically created
Objectives &
Outline
A object comprises data members that specify its state
Classes Data members of an object can be accesses by ”.” (dot)
Objects operator on the object
Data Members
Complex
Rectangle
Stack

Member
Functions
Complex
Rectangle
Stack

this pointer

State of an
Object
Complex
Rectangle
Stack

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Program 11.07/08: Complex Numbers:
Methods
C Program C++ Program
Module 11
// File Name:Complex_func.c: // File Name:Complex_func_c++.cpp:
Partha Pratim #include <stdio.h> #include <iostream>
Das #include <math.h> #include <cmath>
using namespace std;
Objectives &
typedef struct Complex { class Complex { public:
Outline
double re, im; double re, im;
Classes } Complex;
// MEMBER FUNCTIONS / METHODS
Objects // Norm of Complex Number - global fn. // Norm of Complex Number - method
double norm(Complex c) { double norm() {
Data Members return sqrt(c.re*c.re + c.im*c.im); return sqrt(re*re + im*im);
Complex } }
Rectangle // Print number with Norm - global fn. // Print number with Norm - method
Stack void print(Complex c) { void print() {
printf("|%lf+j%lf| = ", c.re, c.im); cout << "|"<< re<< "+j"<< im<< "| = ";
Member
printf("%lf", norm(c)); // Call global cout << norm(); // Call method
Functions
} }
Complex }; // End of class Complex
Rectangle
int main() { Complex c = { 4.2, 5.3 }; int main() { Complex c = { 4.2, 5.3 };
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

Partha Pratim #include <iostream> #include <iostream>


Das using namespace std; using namespace std;

typedef struct { class Point { public:


Objectives & int x; int y; int x; int y;
Outline } Point; };
typedef struct { class Rect { public:
Classes
Point TL; // Top-Left Point TL; // Top-Left
Objects Point BR; // Bottom-Right Point BR; // Bottom-Right
} Rect;
Data Members
Complex // Global function // Method
Rectangle void computeArea(Rect r) { void computeArea() {
Stack cout << abs(r.TL.x - r.BR.x) * cout << abs(TL.x - BR.x) *
abs(r.BR.y - r.TL.y); abs(BR.y - TL.y);
Member } }
Functions };
Complex int main() { int main() {
Rectangle Rect r = { { 0, 2 }, { 5, 7 } }; Rect r = { { 0, 2 }, { 5, 7 } };
Stack
// Global fn. call // Method invocation
this pointer
computeArea(r); r.computeArea();
State of an
Object return 0; return 0;
Complex
} }
Rectangle
----- -----
Stack 25 25

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Program 11.11/12: Stacks:
Methods
Using struct Using class
Module 11
#include <iostream> #include <iostream>
Partha Pratim using namespace std; using namespace std;
Das
typedef struct Stack { class Stack { public:
char data_[100]; int top_; char data_[100]; int top_;
Objectives &
} Stack; // METHODS
Outline
bool empty(const Stack& s) bool empty() { return (top_ == -1); }
Classes { return (s.top_ == -1); }
char top(const Stack& s) char top() { return data_[top_]; }
Objects { return s.data_[s.top_]; }
void push(Stack& s, char x) void push(char x) { data_[++top_] = x; }
Data Members { s.data_[++(s.top_)] = x; }
Complex void pop(Stack& s) { --(s.top_); } void pop() { --top_; }
Rectangle };
Stack int main() { int main() {
Stack s; s.top_ = -1; Stack s; s.top_ = -1;
Member char str[10] = "ABCDE"; int i; char str[10] = "ABCDE"; int i;
Functions
Complex for (i = 0; i < 5; ++i) push(s, str[i]); for (i = 0; i < 5; ++i) s.push(str[i]);
Rectangle
Stack cout << "Reversed String: "; cout << "Reversed String: ";
this pointer while (!empty(s)) { while (!s.empty()) {
cout << top(s); pop(s); cout << s.top(); s.pop();
State of an } }
Object return 0; return 0;
Complex } }
Rectangle ----- -----
Stack Reversed String: EDCBA Reversed String: EDCBA

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Classes

Module 11 A class has operations / member functions / methods


Partha Pratim
Das A class defines a namespace

Objectives & Thus, classes offer data abstraction / encapsulation of


Outline Object Oriented Programming
Classes

Objects

Data Members
Complex
Rectangle
Stack

Member
Functions
Complex
Rectangle
Stack

this pointer

State of an
Object
Complex
Rectangle
Stack

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Objects

Module 11 An object of a class is an instance created according to its


Partha Pratim blue print. Objects can be automatically, statically, or
Das
dynamically created
Objectives &
Outline
A object supports member functions that specify its behavior
Classes Member functions are invoked by ”.” (dot) operator on the
Objects object
Data Members
Complex
Rectangle
Stack

Member
Functions
Complex
Rectangle
Stack

this pointer

State of an
Object
Complex
Rectangle
Stack

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Program 11.13: this Pointer

Module 11 An implicit this pointer holds the address of an object


Partha Pratim
Das this pointer serves as the identity of the object in C++

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

Data Members class X { public: int m1, m2;


void f(int k1, int k2) { // Sample Method
Complex
Rectangle
m1 = k1; // Implicit access w/o ’this’ pointer
Stack this->m2 = k2; // Explicit access w/ ’this’ pointer
cout << "Id = " << this << endl; // Identity (address) of the object
Member }
Functions };
Complex int main() {
Rectangle X a;
Stack a.f(2, 3);
cout << "Addr = " << &a << endl; // Address (identity) of the object
this pointer cout << "a.m1 = " << a.m1 << " a.m2 = " << a.m2 << endl;
return 0;
State of an
}
Object
-----
Complex
Id = 0024F918
Rectangle
Addr = 0024F918
Stack
a.m1 = 2 a.m2 = 3
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 16
this Pointer

Module 11 this pointer is implicitly passed to methods


In Source Code In Binary Code
Partha Pratim
Das class X { void f(int, int); ... } void X::f(X * const this, int, int);

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 17


State of an Object: Complex

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 }

Data Members Complex c1 = {4.2, 5.3};


Complex // STATE 1 of c1 = {4.2, 5.3} // Denotes a tuple / sequence
Rectangle
Stack
A method may change the state:
Member
Functions Complex c = {4.2, 5.3};
Complex // STATE 1 of c = {4.2, 5.3}
Rectangle
Stack c.set_re(6.4);
this pointer // STATE 2 of c = {6.4, 5.3}

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}

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 18


State of an Object: Rectangle

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

Rectangle r = {{0, 5}, {5, 0}}; // Initialization


Objectives & // STATE 1 of r = {{0, 5}, {5, 0}}
Outline { r.TL.x = 0; r.TL.y = 5; r.BR.x = 5; r.BR.y = 0 }
Classes r.TL.y = 9;
// STATE 2 of r = {{0, 9}, {5, 0}}
Objects

Data Members r.computeArea();


// STATE 2 of r = {{0, 9}, {5, 0}} // No change in state
Complex
Rectangle
Stack Point p = {3, 4};
r.BR = p;
Member // STATE 3 of r = {{0, 9}, {3, 4}}
Functions
Complex
Rectangle
Stack

this pointer

State of an
Object
Complex
Rectangle
Stack

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 19


State of an Object: 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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 20


Module Summary

Module 11

Partha Pratim
We have covered the following:
Das

class Complex { public:


Objectives & double re_, im_;
Outline
Class double norm() { // Norm of Complex Number
Classes return sqrt(re_ * re_ + im_ * im_);
Objects }
};
Data Members
Attributes Complex::re_, Complex::re_im_
Complex
Rectangle
Stack Method double Complex::norm();

Member Object Complex c = {2.6, 3.9};


Functions
Complex c.re_ = 4.6;
Rectangle cout << c.im_;
Access
Stack
cout << c.norm;
this pointer
this Pointer double Complex::norm() { cout << this; return ... }
State of an
Object
Complex
Rectangle
Stack

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 21


Instructor and TAs

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 22


Module 12

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 12

Partha Pratim Understand access specifiers in C++ classes to control the


Das
visibility of members
Objectives &
Outline Learn to design with Information Hiding
Access
Specifiers
public and
private

Information
Hiding
Stack (public)
Stack (private)

Get-Set Idiom

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 12

Partha Pratim Access specifiers


Das
public Access Specifier
Objectives & private Access Specifier
Outline
Information Hiding
Access
Specifiers Stack with public data
public and
private Stack with private data
Information
Hiding Get-Set Idiom
Stack (public)
Stack (private)

Get-Set Idiom

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Program 12.01/02: Complex Number:
Access Specification
Public data, Public method Private data, Public method
Module 12
#include <iostream> #include <cmath> #include <iostream> #include <cmath>
Partha Pratim using namespace std; using namespace std;
Das
class Complex { public: double re, im; class Complex { private: double re, im;
public: double norm() { public: double norm() {
Objectives &
return sqrt(re*re + im*im); return sqrt(re*re + im*im);
Outline
} }
Access }; };
Specifiers void print(const Complex& t) { // Global fn. void print(const Complex& t) { // Global fn.
cout << t.re << "+j" << t.im << endl; cout << t.re << "+j" << t.im << endl;
public and
private // ’Complex::re’: cannot access private
// member declared in class ’Complex’
Information
Hiding // ’Complex::im’: cannot access private
Stack (public) // member declared in class ’Complex’
Stack (private) } }
int main() { int main() {
Get-Set Idiom
Complex c = { 4.2, 5.3 }; // Okay Complex c = { 4.2, 5.3 }; // Error
Summary // ’initializing’: cannot convert from
// ’initializer-list’ to ’Complex’
print(c); print(c);
cout << c.norm(); cout << c.norm();
return 0; return 0;
} }
• public data can be accessed by any function • private data can be accessed only by methods
• norm (method) can access (re, im) • norm (method) can access (re, im)
• print (global) can access (re, im) • print (global) cannot access (re, im)
• main (global) can access (re, im) & initialize • main (global) cannot access (re, im) to initialize

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Access Specifiers

Module 12 Classes provide access specifiers for members (data as well as


Partha Pratim function) to enforce data hiding that separates
Das
implementation from interface
Objectives & private - accessible inside the definition of the class
Outline
member functions of the same class
Access
Specifiers public - accessible everywhere
public and
private member functions of the same class
Information member function of a different class
Hiding
Stack (public)
global functions
Stack (private)

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Information Hiding

Module 12

Partha Pratim The private part of a class (attributes and methods)


Das
forms its implementation because the class alone should
Objectives &
Outline
be concerned with it and have the right to change it
Access The public part of a class (attributes and methods)
Specifiers
public and
constitutes its interface which is available to all others for
private

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Information Hiding

Module 12

Partha Pratim For the sake of efficiency in design, we at times, put


Das attributes in public and / or methods in private. In
Objectives & such cases:
Outline
The public attributes should not decide the state of an
Access
Specifiers
object, and
public and
private
The private methods cannot be part of the behavior of
Information
an object
Hiding
Stack (public) We illustrate information hiding through two implementations a
Stack (private)

Get-Set Idiom
stack
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Program 12.03/04: Stack:
Implementations using public data
Using dynamic array Using vector
Module 12
#include <iostream> #include <cstdlib> #include <iostream> #include <vector>
Partha Pratim using namespace std; using namespace std;
Das class Stack { public: class Stack { public:
char *data_; int top_; vector<char> data_; int top_;
public: public:
Objectives &
int empty() { return (top_ == -1); } int empty() { return (top_ == -1); }
Outline
void push(char x) {data_[++top_] = x; } void push(char x) { data_[++top_] = x; }
Access void pop() { --top_; } void pop() { --top_; }
Specifiers char top() { return data_[top_]; } char top() { return data_[top_]; }
}; };
public and
private int main() { int main() {
Stack s; char str[10] = "ABCDE"; Stack s; char str[10] = "ABCDE";
Information
Hiding s.data_ = new char[100]; // Exposed Init s.data_.resize(100); // Exposed Init
Stack (public) s.top_ = - 1; // Exposed Init s.top_ = -1; // Exposed Init
Stack (private)
for(int i = 0; i < 5; ++i) for(int i = 0; i < 5; ++i)
Get-Set Idiom
s.push(str[i]); s.push(str[i]);
Summary while (!s.empty()) { while (!s.empty()) {
cout << s.top(); s.pop(); cout << s.top(); s.pop();
} // Outputs: EDCBA -- Reversed string } // Outputs: EDCBA -- Reversed string
delete [] s.data_; // Exposed De-Init
return 0; return 0;
} }

• 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Program 12.03/04: Stack:
Implementations using public data – Risks
Using dynamic array Using vector
Module 12
#include <iostream> #include <cstdlib> #include <iostream> #include <vector>
Partha Pratim using namespace std; using namespace std;
Das class Stack { public: class Stack { public:
char *data_; int top_; vector<char> data_; int top_;
public: public:
Objectives &
int empty() { return (top_ == -1); } int empty() { return (top_ == -1); }
Outline
void push(char x) {data_[++top_] = x; } void push(char x) { data_[++top_] = x; }
Access void pop() { --top_; } void pop() { --top_; }
Specifiers char top() { return data_[top_]; } char top() { return data_[top_]; }
}; };
public and
private int main() { int main() {
Stack s; char str[10] = "ABCDE"; Stack s; char str[10] = "ABCDE";
Information
Hiding s.data_ = new char[100]; // Exposed Init s.data_.resize(100); // Exposed Init
Stack (public) s.top_ = - 1; // Exposed Init s.top_ = -1; // Exposed Init
Stack (private)
for(int i=0; i<5; ++i) s.push(str[i]); for(int i=0; i<5; ++i) s.push(str[i]);
Get-Set Idiom

Summary s.top_ = 2; // STACK GETS INCONSISTENT s.top_ = 2; // STACK GETS INCONSISTENT

while (!s.empty()) { while (!s.empty()) {


cout << s.top(); s.pop(); cout << s.top(); s.pop();
} // Outputs: CBA -- WRONG!!! } // Outputs: CBA -- WRONG!!!
delete [] s.data_; // Exposed De-Init
return 0; return 0;
} }

• 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

Partha Pratim #include <iostream> #include <iostream>


Das #include <vector>
using namespace std; using namespace std;
class Stack { private: class Stack { private:
Objectives & char *data_; int top_; vector<char> data_; int top_;
Outline public: public:
// Initialization // Initialization
Access
Stack(): data_(new char[100]), top_(-1) {} Stack(): top_(-1) { data_.resize(100); }
Specifiers
// De-Initialization // De-Initialization
public and ~Stack() { delete[] data_; } ~Stack() {};
private
int empty() { return (top_ == -1); } int empty() { return (top_ == -1); }
Information void push(char x) { data_[++top_] = x; } void push(char x) { data_[++top_] = x; }
Hiding void pop() { --top_; } void pop() { --top_; }
Stack (public) char top() { return data_[top_]; } char top() { return data_[top_]; }
Stack (private) }; };
int main() { int main() {
Get-Set Idiom Stack s; char str[10] = "ABCDE"; Stack s; char str[10] = "ABCDE";
for (int i=0; i<5; ++i) s.push(str[i]); for (int i=0; i<5; ++i) s.push(str[i]);
Summary
while (!s.empty()) { while (!s.empty()) {
cout << s.top(); s.pop(); cout << s.top(); s.pop();
} }
return 0; return 0;
} }

• private data hides the internals of the stack (information hiding)


• Data structure codes contained within itself with initialization and de-initialization
• To switch from array to vector or vice-versa the application needs no change
• Application cannot tamper stack – any direct access to top or data is compilation error!
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Interface and Implementation

Module 12 Interface Implementation

Partha Pratim // File: Stack.h // File: Stack.h


Das class Stack { private: // Implementation class Stack { private: // Implementation
char *data_; int top_; char *data_; int top_;
public: // Interface public: // Interface
Objectives & Stack(); Stack();
Outline ~Stack(); ~Stack();
int empty(); int empty();
Access
void push(char x); void push(char x);
Specifiers
void pop(); void pop();
public and
private char top(); char top();
}; };
Information
Hiding // File: Stack.cpp // Implementation
Stack (public) Stack::Stack(): data_(new char[100]), top_(-1) {}
Stack (private) Stack::~Stack() { delete[] data_; }
int Stack::empty() { return (top_ == -1); }
Get-Set Idiom void Stack::push(char x) { data_[++top_] = x; }
void Stack::pop() { --top_; }
Summary
char Stack::top() { return data_[top_]; }

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

Information int writeOnly_; // Like Password -- reset if forgotten


Hiding
Stack (public) int invisible_; // Like top_, data_ in Stack -- keeps internal state
Stack (private)
public:
Get-Set Idiom // get and set methods both to read as well as write readWrite_ member
int getReadWrite() { return readWrite_; }
Summary void setReadWrite(int v) { readWrite_ = v; }

// Only get method to read readOnly_ member - no way to write it


int getReadOnly() { return readOnly_; }

// Only set method to write writeOnly_ member - no way to read it


void setWriteOnly(int v) { writeOnly_ = v; }

// No method accessing invisible_ member directly - no way to read or write it


}
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Module Summary

Module 12

Partha Pratim Access Specifiers helps to control visibility of data


Das
members and methods of a class
Objectives &
Outline The private access specifier can be used to hide
Access information about the implementation details of the data
Specifiers
public and
members and methods
private

Information Get, Set methods are defined to provide an interface to


Hiding
Stack (public)
use and access the data members
Stack (private)

Get-Set Idiom

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Module 13

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

Summary Tanwi Mallick


Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 13

Partha Pratim Understand Object Construction (Initialization)


Das
Understand Object Destruction (De-Initialization)
Objectives &
Outline Understand Object Lifetime
Constructor
Parameterized
Overloaded

Destructor

Default
Constructor

Object
Lifetime
Automatic
Static
Dynamic

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 13

Partha Pratim Constructors


Das
Parameterized
Objectives & Overloaded
Outline

Constructor
Destructor
Parameterized
Overloaded Default Constructor
Destructor Object Lifetime
Default Automatic
Constructor

Object
Array
Lifetime Dynamic
Automatic
Static
Dynamic

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Program 13.01/02: Stack:
Initialization
Public Data Private Data
Module 13
#include <iostream> #include <iostream>
Partha Pratim using namespace std; using namespace std;
Das class Stack { public: // VULNERABLE DATA class Stack { private: // PROTECTED DATA
char data_[10]; int top_; char data_[10]; int top_;
public: public:
Objectives &
void init() { top_ = -1; }
Outline
int empty() { return (top_ == -1); } int empty() { return (top_ == -1); }
Constructor void push(char x) { data_[++top_] = x; } void push(char x) { data_[++top_] = x; }
void pop() { --top_; } void pop() { --top_; }
Parameterized
Overloaded
char top() { return data_[top_]; } char top() { return data_[top_]; }
}; };
Destructor int main() { char str[10] = "ABCDE"; int main() { char str[10] = "ABCDE";
Stack s; Stack s;
Default s.top_ = -1; // Exposed initialization s.init(); // Clean initialization
Constructor
for (int i = 0; i < 5; ++i) for (int i = 0; i < 5; ++i)
Object s.push(str[i]); s.push(str[i]);
Lifetime // s.top_ = 2; // RISK - CORRUPTS STACK // s.top_ = 2; // Compile error - SAFE
Automatic while (!s.empty()) { while (!s.empty()) {
Static cout << s.top(); s.pop(); cout << s.top(); s.pop();
Dynamic } }
Summary return 0; return 0;
} }

• 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Program 13.02/03: Stack:
Initialization
Using init() Using Constructor
Module 13
#include <iostream> #include <iostream>
Partha Pratim using namespace std; using namespace std;
Das class Stack { private: // PROTECTED DATA class Stack { private: // PROTECTED DATA
char data_[10]; int top_; char data_[10]; int top_;
public: public:
Objectives &
void init() { top_ = -1; } Stack() : top_(-1) {} // Initialization
Outline
int empty() { return (top_ == -1); } int empty() { return (top_ == -1); }
Constructor void push(char x) { data_[++top_] = x; } void push(char x) { data_[++top_] = x; }
void pop() { --top_; } void pop() { --top_; }
Parameterized
Overloaded
char top() { return data_[top_]; } char top() { return data_[top_]; }
}; };
Destructor int main() { char str[10] = "ABCDE"; int main() { char str[10] = "ABCDE";
Stack s; Stack s; // Init by Stack::Stack() call
Default s.init(); // Clean initialization
Constructor
for (int i = 0; i < 5; ++i) for (int i = 0; i < 5; ++i)
Object s.push(str[i]); s.push(str[i]);
Lifetime // s.top_ = 2; // Compile error - SAFE
Automatic while (!s.empty()) { while (!s.empty()) {
Static cout << s.top(); s.pop(); cout << s.top(); s.pop();
Dynamic } }
Summary return 0; return 0;
} }

• init() serves no visible purpose – • Can initialization be made a part of instantiation?


application may forget to call
• If application misses to call init(), we • Yes. Constructor is implicitly called at
have a corrupt stack instantiation as set by the compiler

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Program 13.04/05: Stack: Constructor
Automatic Array Dynamic Array
Module 13
#include <iostream> using namespace std; #include <iostream> using namespace std;
Partha Pratim class Stack { private: class Stack { private:
Das char data_[10]; int top_; // Automatic char *data_; int top_; // Dynamic
public: public:
Stack(); // Constructor Stack(); // Constructor
Objectives &
// More Stack methods // More Stack methods
Outline
}; };
Constructor Stack::Stack(): // Initialization List Stack::Stack(): data_(new char[10]), // Init
top_(-1) { top_(-1) { // List
Parameterized
Overloaded
cout << "Stack::Stack() called" << endl; cout << "Stack::Stack() called" << endl;
} }
Destructor int main() { char str[10] = "ABCDE"; int main() { char str[10] = "ABCDE";
Stack s; // Init by Stack::Stack() call Stack s; // Init by Stack::Stack() call
Default
Constructor for (int i=0; i<5; ++i) s.push(str[i]); for (int i=0; i<5; ++i) s.push(str[i]);
while (!s.empty()) { while (!s.empty()) {
Object cout << s.top(); s.pop(); cout << s.top(); s.pop();
Lifetime } }
Automatic return 0; return 0;
Static } }
Dynamic ----- -----
Summary Stack::Stack() called Stack::Stack() called
EDCBA EDCBA

• top initialized to -1 in initialization list • top initialized to -1 in initialization list


• data [10] initialized by default (automatic) • data initialized to new char[10] in init list
• Stack::Stack() called automatically when control passes Stack s; – Guarantees initialization

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Constructor: Contrasting with Member Functions
Constructor Member Function
Module 13
Is a member function with this pointer Has implicit this pointer
Partha Pratim
Das Name is same as the name of the class Any name different from name of class
class Stack { public: class Stack { public:
Objectives & Stack(); int empty();
Outline }; };
Has no return type Must have a return type
Constructor
Stack::Stack(); // Not even void int Stack::empty();
Parameterized
Overloaded No return; hence has no return statement Must have at least one return statement
Destructor Stack::Stack(): top_(-1) int Stack::empty()
{ } // Returns implicitly { return (top_ == -1); }
Default
Constructor void pop()
{ --top_; } // Implicit return
Object
Lifetime Initializer list to initialize the data members Not applicable
Automatic Stack::Stack(): // Initializer list
Static data_(new char[10]), // Init data_
Dynamic top_(-1) // Init top_
{ }
Summary
Implicit call by instantiation / operator new Explicit call by the object
Stack s; // Calls Stack::Stack() s.empty(); // Calls Stack::empty(&s)
May have any number of parameters May have any number of parameters
Can be overloaded Can be overloaded

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Program 13.06: Complex:
Parameterized Constructor
Module 13 #include <iostream>
using namespace std;
Partha Pratim
Das class Complex { private: double re_, im_;
public:
Complex(double re, double im): // Ctor w/ params
Objectives & re_(re), im_(im) // Params used to initialize
Outline {}
double norm() { return sqrt(re_*re_ + im_*im_); }
Constructor
Parameterized void print() {
Overloaded
cout << "|" << re_ << "+j" << im_ << "| = ";
Destructor cout << norm() << endl;
}
Default };
Constructor int main() {
Complex c(4.2, 5.3), // Complex::Complex(4.2, 5.3)
Object d = { 1.6, 2.9 }; // Complex::Complex(1.6, 2.9)
Lifetime
Automatic c.print();
Static d.print();
Dynamic
return 0;
Summary
}
-----
|4.2+j5.3| = 6.7624
|1.6+j2.9| = 3.3121

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Program 13.07: Complex:
Constructor with default parameters
Module 13 #include <iostream>
using namespace std;
Partha Pratim
Das class Complex { private: double re_, im_;
public:
Complex(double re = 0.0, double im = 0.0) : // Ctor w/ default params
Objectives & re_(re), im_(im) // Params used to initialize
Outline {}
double norm() { return sqrt(re_*re_ + im_*im_); }
Constructor
Parameterized void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
Overloaded
};
Destructor int main() {
Complex c1(4.2, 5.3), // Complex::Complex(4.2, 5.3) -- both parameters explicit
Default c2(4.2), // Complex::Complex(4.2, 0.0) -- second parameter default
Constructor c3; // Complex::Complex(0.0, 0.0) -- both parameters default

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Program 13.08: Stack:
Constructor with default parameters
Module 13 #include <iostream>
using namespace std;
Partha Pratim
Das class Stack { private: char *data_; int top_;
public:
Stack(size_t = 10); // Size of data_ defaulted
Objectives &
Outline int empty() { return (top_ == -1); }
void push(char x) { data_[++top_] = x; }
Constructor
void pop() { --top_; }
Parameterized char top() { return data_[top_]; }
Overloaded
};
Destructor Stack::Stack(size_t s) : data_(new char[s]), // Array of size s allocated
top_(-1)
Default { cout << "Stack created with max size = " << s << endl; }
Constructor
int main() {
Object char str[] = "ABCDE";
Lifetime Stack s(strlen(str)); // Create a stack large enough for the problem
Automatic
Static for (int i = 0; i<5; ++i) s.push(str[i]);
Dynamic while (!s.empty()) {
cout << s.top(); s.pop();
Summary
}
return 0;
}
-----
Stack created with max size = 5
EDCBA

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Program 13.09: Complex:
Overloaded Constructors
Module 13 #include <iostream>
using namespace std;
Partha Pratim
Das class Complex { private: double re_, im_;
public:
Complex(double re, double im): re_(re), im_(im) {} // Two parameters
Objectives & Complex(double re): re_(re), im_(0.0) {} // One parameter
Outline Complex(): re_(0.0), im_(0.0) {} // No parameter
Constructor
double norm() { return sqrt(re_*re_ + im_*im_); }
Parameterized
Overloaded
void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
Destructor };
int main() {
Default Complex c1(4.2, 5.3), // Complex::Complex(4.2, 5.3)
Constructor c2(4.2), // Complex::Complex(4.2)
c3; // Complex::Complex()
Object
Lifetime c1.print();
Automatic c2.print();
Static c3.print();
Dynamic
return 0;
Summary
}
-----
|4.2+j5.3| = 6.7624
|4.2+j0| = 4.2
|0+j0| = 0

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Program 13.10/11: Stack: Destructor
Automatic Array Dynamic Array
Module 13
#include <iostream> using namespace std; #include <iostream> using namespace std;
Partha Pratim class Stack { private: class Stack { private:
Das char *data_; int top_; // Dynamic char *data_; int top_; // Dynamic
public: Stack(); // Constructor public: Stack(); // Constructor
void de_init() { delete [] data_; } ~Stack(); // Destructor
Objectives &
// More Stack methods // More Stack methods
Outline
}; };
Constructor Stack::Stack(): data_(new char[10]), top_(-1) Stack::Stack(): data_(new char[10]), top_(-1)
{ cout << "Stack::Stack() called\n"; } { cout << "Stack::Stack() called\n"; }
Parameterized
Overloaded
Stack::~Stack() {
cout << "\nStack::~Stack() called\n";
Destructor delete data_;
}
Default int main() { char str[10] = "ABCDE"; int main() { char str[10] = "ABCDE";
Constructor Stack s; // Init by Stack::Stack() call Stack s; // Init by Stack::Stack() call
Object // Reverse string using Stack // Reverse string using Stack
Lifetime de_init();
Automatic return 0; return 0;
Static } } // De-Init by Stack::~Stack() call
Dynamic ----- -----
Summary Stack::Stack() called Stack::Stack() called
EDCBA EDCBA
Stack::~Stack() called

• Dynamically allocated data leaks unless • Can de-initialization (release of data ) be


released before program loses scope of s a part of scope rules?
• Application may forget to call de init(); • Yes. Destructor is implicitly called at end of
Also, when should de init() be called? scope
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Destructor: Contrasting with Member Functions
Destructor Member Function
Module 13
Is a member function with this pointer Has implicit this pointer
Partha Pratim
Das Name is ˜ followed by the name of the class Any name different from name of class
class Stack { public: class Stack { public:
Objectives & ~Stack(); int empty();
Outline }; };
Has no return type Must have a return type
Constructor
Stack::~Stack(); // Not even void int Stack::empty();
Parameterized
Overloaded No return; hence has no return statement Must have at least one return statement
Destructor Stack::~Stack() int Stack::empty()
{ } // Returns implicitly { return (top_ == -1); }
Default Implicitly called at end of scope or by Explicit call by the object
Constructor operator delete. May be called explicitly by
Object the object (rare)
Lifetime { s.empty(); // Calls Stack::empty(&s)
Automatic Stack s;
Static // ...
Dynamic } // Calls Stack::~Stack(&s)
Summary No parameter is allowed - unique for the class May have any number of parameters
Cannot be overloaded Can be overloaded

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Default Constructor / Destructor

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Program 13.12: Complex: Default Constructor
#include <iostream>
Module 13 using namespace std;

Partha Pratim class Complex {


Das private: double re_, im_; // private data
public:
double norm() { return sqrt(re_*re_ + im_*im_); }
Objectives &
void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
Outline
void set(double re, double im) { re_ = re; im_ = im; }
Constructor };
Parameterized
int main() {
Overloaded
Complex c; // Free constructor from compiler
Destructor // Initialization with garbage

Default c.print(); // Print initial value - garbage


Constructor c.set(4.2, 5.3); // Set proper components
c.print(); // Print values set
Object
Lifetime return 0;
Automatic } // Free destuctor from compiler
Static -----
Dynamic |-9.25596e+061+j-9.25596e+061| = 1.30899e+062
Summary |4.2+j5.3| = 6.7624

• User has provided no constructor / destructor


• Compiler provides default (free) constructor / destructor
• Compiler-provided constructor does nothing – components have garbage values
• Compiler-provided destructor does nothing

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Program 13.13: Complex: Default Constructor
#include <iostream>
Module 13 using namespace std;

Partha Pratim class Complex { private: double re_, im_;


Das public:
Complex(): re_(0.0), im_(0.0) // Default Ctor
{ cout << "Ctor: (" << re_ << ", " << im_ << ")" << endl; }
Objectives &
~Complex() // Dtor
Outline
{ cout << "Dtor: (" << re_ << ", " << im_ << ")" << endl; }
Constructor double norm() { return sqrt(re_*re_ + im_*im_); }
void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
Parameterized
void set(double re, double im) { re_ = re; im_ = im; }
Overloaded
};
Destructor int main() {
Complex c; // Default constructor -- user provided
Default
Constructor c.print(); // Print initial values
c.set(4.2, 5.3); // Set components
Object c.print(); // Print values set
Lifetime
Automatic return 0;
Static } // Destuctor
Dynamic -----
Summary Ctor: (0, 0)
|0+j0| = 0
|4.2+j5.3| = 6.7624
Dtor: (4.2, 5.3)

• User has provided a default constructor

NPTEL MOOCs Programming in C++ Partha Pratim Das 16


Object Lifetime: When is an Object ready?
How long can it be used?
Application Class Code
Module 13
void MyFunc() // E1: Allocation of c on Stack Complex::Complex(double re = 0.0, // Ctor
Partha Pratim { double im = 0.0):
Das ... re_(re), im_(im) // E3: Initialization
Complex c; // E2: Ctor called { // E4: Object Lifetime STARTS
Objectives & ... cout << "Ctor:" << endl;
Outline }

Constructor c.norm(); // E5: Use double Complex::norm() // E6


Parameterized ... { return sqrt(re_*re_ + im_*im_); }
Overloaded

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Object Lifetime

Module 13 Execution Stages


Partha Pratim Memory Allocation and Binding
Das Constructor Call and Execution
Objectives &
Object Use
Outline Destructor Call and Execution
Constructor Memory De-Allocation and De-Binding
Parameterized
Overloaded Object Lifetime
Destructor
Starts with execution of Constructor Body
Default
Constructor
Must follow Memory Allocation
As soon as Initialization ends and control enters
Object
Lifetime Constructor Body
Automatic
Static
Ends with execution of Destructor Body
Dynamic
As soon as control leaves Destructor Body
Summary
Must precede Memory De-allocation
For Objects of Built-in / Pre-Defined Types
No Explicit Constructor / Destructor
Lifetime spans from object definition to end of scope
NPTEL MOOCs Programming in C++ Partha Pratim Das 18
Program 13.14: Complex: Object Lifetime:
Automatic
#include <iostream>
Module 13
using namespace std;
class Complex { private: double re_, im_;
Partha Pratim public:
Das Complex(double re = 0.0, double im = 0.0): re_(re), im_(im) // Ctor
{ cout << "Ctor: (" << re_ << ", " << im_ << ")" << endl; }
Objectives &
Outline ~Complex() // Dtor
{ cout << "Dtor: (" << re_ << ", " << im_ << ")" << endl; }
Constructor
Parameterized double norm() { return sqrt(re_*re_ + im_*im_); }
Overloaded void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
};
Destructor int main() {
Default Complex c(4.2, 5.3), d(2.4); // Complex::Complex() called -- c, then d -- objects ready
Constructor
c.print(); // Using objects
Object d.print();
Lifetime
Automatic
return 0;
Static } // Scope over, objects no more available.
Dynamic // Complex::~Complex() called -- d then c
// Note the reverse order!
Summary -----
Ctor: (4.2, 5.3)
Ctor: (2.4, 0)
|4.2+j5.3| = 6.7624
|2.4+j0| = 2.4
Dtor: (2.4, 0)
Dtor: (4.2, 5.3)
NPTEL MOOCs Programming in C++ Partha Pratim Das 19
Program 13.15: Complex: Object Lifetime:
Automatic: Array of Objects
#include <iostream>
Module 13
using namespace std;
class Complex { private: double re_, im_;
Partha Pratim public:
Das Complex(double re = 0.0, double im = 0.0) : re_(re), im_(im) // Ctor
{ cout << "Ctor: (" << re_ << ", " << im_ << ")" << endl; }
Objectives & ~Complex() // Dtor
Outline { cout << "Dtor: (" << re_ << ", " << im_ << ")" << endl; }

Constructor void opComplex(double i) { re_ += i; im_ += i; } // Some operation with Complex


Parameterized
Overloaded double norm() { return sqrt(re_*re_ + im_*im_); }
void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
Destructor };
Default int main() {
Constructor Complex c[3]; // Default ctor Complex::Complex() called thrice -- c[0], c[1], c[2]

Object for (int i = 0; i < 3; ++i) { c[i].opComplex(i); c[i].print(); } // Use array


Lifetime return 0;
Automatic
} // Scope over. Complex::~Complex() called thrice -- c[2], c[1], c[0] -- reverse order
Static -----
Dynamic Ctor: (0, 0)
Ctor: (0, 0)
Summary Ctor: (0, 0)
|0+j0| = 0
|1+j1| = 1.41421
|2+j2| = 2.82843
Dtor: (2, 2)
Dtor: (1, 1)
Dtor: (0, 0)
NPTEL MOOCs Programming in C++ Partha Pratim Das 20
Program 13.16: Complex: Object Lifetime:
Static
#include <iostream>
Module 13 using namespace std;

Partha Pratim class Complex { private: double re_, im_;


Das public:
Complex(double re = 0.0, double im = 0.0): re_(re), im_(im) // Ctor
{ cout << "Ctor: (" << re_ << ", " << im_ << ")" << endl; }
Objectives &
~Complex() // Dtor
Outline
{ cout << "Dtor: (" << re_ << ", " << im_ << ")" << endl; }
Constructor double norm() { return sqrt(re_*re_ + im_*im_); }
void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
Parameterized
};
Overloaded

Destructor Complex c(4.2, 5.3); // Static (global) object


// Constructed before main starts
Default // Destructed after main ends
Constructor int main() {
cout << "main() Starts" << endl;
Object Complex d(2.4); // Ctor for d
Lifetime ----- OUTPUT -----
Automatic
Ctor: (4.2, 5.3)
c.print(); // Use static object
Static main() Starts
d.print(); // Use local object
Dynamic Ctor: (2.4, 0)
|4.2+j5.3| = 6.7624
Summary return 0;
|2.4+j0| = 2.4
} // Dtor for d
Dtor: (2.4, 0)
Dtor: (4.2, 5.3)
// Dtor for c

NPTEL MOOCs Programming in C++ Partha Pratim Das 21


Program 13.17: Complex: Object Lifetime:
Dynamic
Module 13 #include <iostream>
using namespace std;
class Complex { private: double re_, im_;
Partha Pratim
public:
Das
Complex(double re = 0.0, double im = 0.0): re_(re), im_(im) // Ctor
{ cout << "Ctor: (" << re_ << ", " << im_ << ")" << endl; }
Objectives & ~Complex() // Dtor
Outline { cout << "Dtor: (" << re_ << ", " << im_ << ")" << endl; }
double norm() { return sqrt(re_*re_ + im_*im_); }
Constructor void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
Parameterized };
Overloaded int main() { unsigned char buf[100]; // Buffer for placement of objects
Complex* pc = new Complex(4.2, 5.3); // operator new: allocates memory, calls Ctor
Destructor
Complex* pd = new Complex[2]; // operator new []: allocates memory,
Default // calls default Ctor twice
Constructor Complex* pe = new (buf) Complex(2.6, 3.9); // operator placement new: only calls Ctor
// no allocation of memory, uses buf
Object // Use objects
----- OUTPUT -----
Lifetime pc->print();
Ctor: (4.2, 5.3)
Automatic pd[0].print(); pd[1].print();
Ctor: (0, 0)
Static pe->print();
Ctor: (0, 0)
Dynamic Ctor: (2.6, 3.9)
// Release of objects - can be done in any order
Summary |4.2+j5.3| = 6.7624
delete pc; // delete: calls Dtor, release memory
|0+j0| = 0
delete [] pd; // delete[]: calls 2 Dtor’s, release mem
|0+j0| = 0
pe->~Complex(); // No delete: explicit call to Dtor
|2.6+j3.9| = 4.68722
// Use with extreme care
Dtor: (4.2, 5.3)
return 0;
Dtor: (0, 0)
}
Dtor: (0, 0)
Dtor: (2.6, 3.9)
NPTEL MOOCs Programming in C++ Partha Pratim Das 22
Module Summary

Module 13 Objects are initialized by Constructors


Partha Pratim
Das
Constructors can be Parameterized and can be Overloaded
Default Constructor does not take any parameter. It is
Objectives &
Outline necessary for defining arrays of objects
Constructor
Parameterized
Objects are cleaned-up by Destructors. Destructor for a
Overloaded
class is unique
Destructor

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 23


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 24


Module 14

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 14

Partha Pratim More on Object Lifetime


Das
Understand Copy Construction
Objectives &
Outline Understand Copy Assignment Operator
Lifetime
Examples Understand Shallow and Deep 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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 14

Partha Pratim Lifetime Examples


Das
Copy Constructor
Objectives &
Outline
Input Parameters
Lifetime
Call-by-Value
Examples Initialization List
String
Date Copy with Pointers – Shallow and Deep Copy
Rect
Name & Address Copy Assignment Operator
CreditCard

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Program 14.01: Order of Initialization –
Order of Data Members
#include <iostream> #include <iostream>
Module 14 using namespace std; using namespace std;

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Program 14.02/03: A Simple String Class
C Style C++ Style
Module 14
#include <iostream> #include <iostream>
using namespace std; using namespace std;
Partha Pratim
Das
struct String { class String {
char *str_; // Container char *str_; // Container
Objectives & size_t len_; // Length size_t len_; // Length
Outline }; public:
String(char *s) : str_(strdup(s)), // Uses malloc()
Lifetime void print(const String& s) { len_(strlen(str_))
Examples cout << s.str_ << ": " { cout << "ctor: "; print(); }
String << s.len_ << endl; ~String() {
Date } cout << "dtor: "; print();
Rect int main() { free(str_); // To match malloc() in strdup()
Name & Address String s; }
CreditCard void print() { cout << "(" << str_ << ": "
Copy // Init data members << len_ << ")" << endl; }
Constructor s.str_ = strdup("Partha"); size_t len() { return len_; }
s.len_ = strlen(s.str_); };
Call by value
int main() {
Signature
print(s); String s = "Partha"; // Ctor called
Data members
Free Copy
s.print();
Constructor return 0; return 0;
} }
Copy ----- -----
Assignment Partha: 6 ctor: (Partha: 6)
Operator (Partha: 6)
Copy Pointer dtor: (Partha: 6)
Self-Copy
Signature • Note the order of initialization between str and len . What if we swap them?
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 5
Program 14.04: A Simple String Class –
Fails for wrong order of data members
#include <iostream>
Module 14 using namespace std;

Partha Pratim class String {


Das size_t len_; // Swapped members cause program crash (unhandled exception)
char *str_;
public:
Objectives &
String(char *s) : str_(strdup(s)), len_(strlen(str_)) { cout << "ctor: "; print(); }
Outline
~String() { cout << "dtor: "; print(); free(str_); }
Lifetime void print() { cout << "(" << str_ << ": " << len_ << ")" << endl; }
Examples };
int main() {
String
String s = "Partha";
Date
Rect
s.print();
Name & Address
return 0;
CreditCard }

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Program 14.05: A Simple Date Class
#include <iostream>
Module 14 using namespace std;

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Program 14.06: Point and Rect Classes:
Lifetime of Data Members or Embedded Objects
#include <iostream>
Module 14 using namespace std;
class Point { class Rect {
Partha Pratim
int x_; Point TL_;
Das
int y_; Point BR_;
public: public:
Objectives & Point(int x, int y): Rect(int tlx, int tly, int brx, int bry):
Outline x_(x), y_(y) TL_(tlx, tly), BR_(brx, bry)
{ cout << "Point ctor: "; { cout << "Rect ctor: ";
Lifetime print(); cout << endl; } print(); cout << endl; }
Examples ~Point() { cout << "Point dtor: "; ~Rect() { cout << "Rect dtor: ";
String print(); cout << endl; } print(); cout << endl; }
Date void print() void print()
Rect { cout << "(" << x_ << ", " { cout << "["; TL_.print(); cout
Name & Address << y_ << ")"; } << " "; BR_.print(); cout << "]"; }
CreditCard }; };
Copy -----
Constructor int main() { Point ctor: (0, 2)
Call by value Rect r (0, 2, 5, 7); Point ctor: (5, 7)
Signature Rect ctor: [(0, 2) (5, 7)]
Data members cout << endl; r.print(); cout << endl;
Free Copy [(0, 2) (5, 7)]
Constructor cout << endl;
Copy return 0; Rect dtor: [(0, 2) (5, 7)]
Assignment } Point dtor: (5, 7)
Operator Point dtor: (0, 2)
Copy Pointer
• Attempt is to construct a Rect object
Self-Copy
• That, in turn, needs constructions of Point data members (or embedded objects) – TL and BR respectively
Signature • Destruction, initiated at the end of scope of destructor’s body, naturally follows a reverse order

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Program 14.07: Name & Address Classes
#include <iostream>
Module 14 using namespace std;

Partha Pratim #include "String.h"


Das #include "Date.h"

class Name { String firstName_, lastName_;


Objectives &
public:
Outline
Name(const char* fn, const char* ln) : firstName_(fn), lastName_(ln)
Lifetime { cout << "Name ctor: "; print(); cout << endl; }
Examples ~Name() { cout << "Name dtor: "; print(); cout << endl; }
void print()
String
{ firstName_.print(); cout << " "; lastName_.print(); }
Date
Rect
};
Name & Address
class Address {
CreditCard unsigned int houseNo_;
String street_, city_, pin_;
Copy public:
Constructor Address(unsigned int hn, const char* sn, const char* cn, const char* pin) :
Call by value houseNo_(hn), street_(sn), city_(cn), pin_(pin)
Signature { cout << "Address ctor: "; print(); cout << endl; }
Data members ~Address() { cout << "Address dtor: "; print(); cout << endl; }
Free Copy void print() {
Constructor cout << houseNo_ << " ";
Copy street_.print(); cout << " ";
Assignment city_.print(); cout << " ";
Operator pin_.print();
Copy Pointer
}
Self-Copy
};
Signature

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Program 14.07: CreditCard Class
class CreditCard { typedef unsigned int UINT;
Module 14 char cardNumber_[17]; // 16-digit (character) card number as C-string
Name holder_;
Partha Pratim Address addr_;
Das Date issueDate_, expiryDate_;
UINT cvv_;
public:
Objectives &
CreditCard(const char* cNumber, const char* fn, const char* ln,
Outline
unsigned int hn, const char* sn, const char* cn, const char* pin,
Lifetime UINT issueMonth, UINT issueYear, UINT expiryMonth, UINT expiryYear, UINT cvv) :
Examples holder_(fn, ln), addr_(hn, sn, cn, pin),
issueDate_(1, issueMonth, issueYear),
String
Date
expiryDate_(1, expiryMonth, expiryYear), cvv_(cvv)
Rect { strcpy(cardNumber_, cNumber); cout << "CC ctor: "; print(); cout << endl; }
Name & Address ~CreditCard() { cout << "CC dtor: "; print(); cout << endl; }
CreditCard void print() {
cout << cardNumber_ << " ";
Copy holder_.print(); cout << " ";
Constructor addr_.print(); cout << " ";
Call by value issueDate_.print(); cout << " ";
Signature expiryDate_.print(); cout << " ";
Data members cout << cvv_;
Free Copy }
Constructor
};
Copy int main() {
Assignment CreditCard cc("5321711934640027", "Sharlock", "Holmes",
Operator 221, "Baker Street", "London", "NW1 6XE", 7, 2014, 12, 2016, 811);
Copy Pointer cout << endl; cc.print(); cout << endl << endl;;
Self-Copy return 0;
Signature }

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Program 14.07: CreditCard Class: Lifetime Chart
Construction of Objects typedef unsigned int UINT;
Module 14 class CreditCard { char cardNumber_[17];
String: Sharlock Name holder_;
Partha Pratim String: Holmes Address addr_;
Das Name: Sharlock Holmes Date issueDate_, expiryDate_;
String: Baker Street UINT cvv_; };
String: London class Name { String firstName_, lastName_; };
Objectives &
String: NW1 6XE class Address { unsigned int houseNo_;
Outline
Address: 221 Baker Street London NW1 6XE String street_, city_, pin_; };
Lifetime Date: 1/Jul/2014 class Date { enum Month;
Examples Date: 1/Dec/2016 UINT date_; Month month_; UINT year_; };
String CC: 5321711934640027 Sharlock Holmes 221 Baker Street London NW1 6XE 1/Jul/2014 1/Dec/2016 811
Date
Rect Use of Object
Name & Address
CreditCard
5321711934640027 Sharlock Holmes 221 Baker Street London NW1 6XE 1/Jul/2014 1/Dec/2016 811
Copy
Constructor Destruction of Objects
Call by value
Signature
~CC: 5321711934640027 Sharlock Holmes 221 Baker Street London NW1 6XE 1/Jul/2014 1/Dec/2016 811
Data members
~Date: 1/Dec/2016
Free Copy
Constructor ~Date: 1/Jul/2014
~Address: 221 Baker Street London NW1 6XE
Copy ~String: NW1 6XE
Assignment ~String: London
Operator ~String: Baker Street
Copy Pointer ~Name: Sharlock Holmes
Self-Copy ~String: Holmes
Signature ~String: Sharlock
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Copy Constructor

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Program 14.08: Complex: Copy Constructor
#include <iostream>
Module 14 #include <cmath>
using namespace std;
Partha Pratim class Complex { double re_, im_;
Das public:
Complex(double re, double im) : re_(re), im_(im) // Constructor
{ cout << "Complex ctor: "; print(); }
Objectives &
Complex(const Complex& c) : re_(c.re_), im_(c.im_) // Copy Constructor
Outline
{ cout << "Complex copy ctor: "; print(); }
Lifetime ~Complex() { cout << "Complex dtor: "; print(); }
Examples double norm() { return sqrt(re_*re_ + im_*im_); }
void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
String
};
Date
Rect
int main() {
Name & Address
Complex c1(4.2, 5.3), // Constructor - Complex(double, double)
CreditCard c2(c1), // Copy Constructor - Complex(const Complex&)
c3 = c2; // Copy Constructor - Complex(const Complex&)
Copy
Constructor c1.print(); c2.print(); c3.print();
Call by value return 0;
Signature }
Data members -----
Free Copy Complex ctor: |4.2+j5.3| = 6.7624 // Ctor: c1
Constructor Complex copy ctor: |4.2+j5.3| = 6.7624 // CCtor: c2 of c1
Copy Complex copy ctor: |4.2+j5.3| = 6.7624 // CCtor: c3 of c2
Assignment |4.2+j5.3| = 6.7624 // c1
Operator |4.2+j5.3| = 6.7624 // c2
Copy Pointer
|4.2+j5.3| = 6.7624 // c3
Self-Copy
Complex dtor: |4.2+j5.3| = 6.7624 // Dtor: c3
Signature Complex dtor: |4.2+j5.3| = 6.7624 // Dtor: c2
Complex dtor: |4.2+j5.3| = 6.7624 // Dtor: c1
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 13
Why do we need Copy Constructor?

Module 14 Consider the function call mechanisms in C++:


Partha Pratim Call-by-reference: Set a reference to the actual parameter
Das as a formal parameter. Both the formal parameter and the
Objectives &
actual parameter share the same location (object)
Outline

Lifetime Return-by-reference: Set a reference to the computed


Examples
String value as a return value. Both the computed value and the
Date
Rect
return value share the same location (object)
Name & Address
CreditCard

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Program 14.09: Complex: Call by value

Module 14 #include <iostream>


#include <cmath>
Partha Pratim using namespace std;
Das
class Complex { double re_, im_;
public:
Objectives & Complex(double re, double im) : re_(re), im_(im) // Constructor
Outline { cout << "ctor: "; print(); }
Complex(const Complex& c) : re_(c.re_), im_(c.im_) // Copy Constructor
Lifetime
{ cout << "copy ctor: "; print(); }
Examples
~Complex() { cout << "dtor: "; print(); }
String double norm() { return sqrt(re_*re_ + im_*im_); }
Date void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
Rect
};
Name & Address
void Display(Complex c_param) { // Call by value
CreditCard
cout << "Display: "; c_param.print();
Copy }
Constructor int main() {
Call by value Complex c(4.2, 5.3); // Constructor - Complex(double, double)
Signature
Data members Display(c); // Copy Constructor called to copy c to c_param
Free Copy
Constructor return 0;
}
Copy
-----
Assignment
ctor: |4.2+j5.3| = 6.7624 // Ctor of c in main()
Operator
copy ctor: |4.2+j5.3| = 6.7624 // Ctor c_param as copy of c, call Display()
Copy Pointer
Display: |4.2+j5.3| = 6.7624 // c_param
Self-Copy
dtor: |4.2+j5.3| = 6.7624 // Dtor c_param on exit from Display()
Signature
dtor: |4.2+j5.3| = 6.7624 // Dtor of c on exit from main()
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 15
Signature of Copy Constructors

Module 14 Signature of a Copy Constructor can be one of:


Partha Pratim
Das MyClass(const MyClass& other); // Common
// Source cannot be changed
Objectives & MyClass(MyClass& other); // Occasional
Outline
// Source needs to change
Lifetime MyClass(volatile const MyClass& other); // Rare
Examples MyClass(volatile MyClass& other); // Rare
String
Date
Rect
Name & Address
None of the following are copy constructors, though they can copy:
CreditCard

Copy MyClass(MyClass* other);


Constructor MyClass(const MyClass* other);
Call by value
Signature
Data members Why the parameter to a copy constructor must be passed as
Free Copy
Constructor Call-by-Reference?
Copy
Assignment MyClass(MyClass other);
Operator
Copy Pointer
Self-Copy The above is an infinite loop as the call to copy constructor itself needs to
Signature
make copy for the Call-by-Value mechanism.
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 16
Program 14.10: Point and Rect Classes:
Default, Copy and Overloaded Constructors
#include <iostream>
Module 14 using namespace std;
class Point { int x_; int y_; public:
Partha Pratim Point(int x, int y) : x_(x), y_(y) // Constructor (Ctor)
Das { cout << "Point ctor: "; print(); cout << endl; }
Point() : x_(0), y_(0) // Default Constructor (DCtor)
{ cout << "Point ctor: "; print(); cout << endl; }
Objectives &
Point(const Point& p) : x_(p.x_), y_(p.y_) // Copy Constructor (CCtor)
Outline
{ cout << "Point cctor: "; print(); cout << endl; }
Lifetime ~Point() { cout << "Point dtor: "; print(); cout << endl; } // Destructor (Dtor)
Examples void print() { cout << "(" << x_ << ", " << y_ << ")"; }
};
String
class Rect { Point TL_; Point BR_; public:
Date
Rect
Rect(int tlx, int tly, int brx, int bry):
Name & Address
TL_(tlx, tly), BR_(brx, bry) // Ctor - Uses Ctor for Point
CreditCard { cout << "Rect ctor: "; print(); cout << endl; }
Rect(const Point& p_tl, const Point& p_br): TL_(p_tl), BR_(p_br) // Ctor
Copy { cout << "Rect ctor: "; print(); cout << endl; } // Uses CCtor for Point
Constructor Rect(const Point& p_tl, int brx, int bry): TL_(p_tl), BR_(brx, bry) // Ctor
Call by value { cout << "Rect ctor: "; print(); cout << endl; } // CCtor for Point
Signature Rect() { cout << "Rect ctor: "; print(); cout << endl; } // Default Ctor
Data members Rect(const Rect& r): TL_(r.TL_), BR_(r.BR_) // Copy Ctor
Free Copy { cout << "Rect cctor: "; print(); cout << endl; }
Constructor ~Rect() { cout << "Rect dtor: "; print(); cout << endl; } // Dtor
Copy void print() { cout << "["; TL_.print(); cout << " "; BR_.print(); cout << "]"; }
Assignment };
• When parameter (tlx, tly) is set to TL by TL (tlx, tly): parameterized Ctor of Point is involved
Operator
• When parameter p tl is set to TL by TL (p tl): CCtor of Point is involved
Copy Pointer
• When TL is set by default in DCtor of Rect: DCtor of Point is involved
Self-Copy
• When member r.TL is set to TL by TL (r.TL ) in CCtor of Rect: CCtor of Point is involved
Signature

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Program 14.10: Rect Class: Trace of Object
Lifetimes
Code Output Lifetime Remarks
Module 14 int main() {
Rect r1(0, 2, 5, 7); Point ctor: (0, 2) Point r1.TL
Partha Pratim //Rect(int, int, int, int) Point ctor: (5, 7) Point r1.BR
Das Rect ctor: [(0, 2) (5, 7)] Rect r1
Rect r2(Point(3, 5), Point ctor: (6, 9) Point t1 Second parameter
Objectives & Point(6, 9)); Point ctor: (3, 5) Point t2 First parameter
Outline //Rect(Point&, Point&) Point cctor: (3, 5) r2.TL = t2 Copy to r2.TL
Point cctor: (6, 9) r2.BR = t1 Copy to r2.BR
Lifetime Rect ctor: [(3, 5) (6, 9)] Rect r2
Examples Point dtor: (3, 5) ˜Point t2 First parameter
String Point dtor: (6, 9) ˜Point t1 Second parameter
Date Rect r3(Point(2, 2), 6, 4); Point ctor: (2, 2) Point t3 First parameter
Rect //Rect(Point&, int, int) Point cctor: (2, 2) r3.TL = t3 Copy to r3.TL
Name & Address Point ctor: (6, 4) Point r3.BR
CreditCard Rect ctor: [(2, 2) (6, 4)] Rect r3
Point dtor: (2, 2) ˜Point t3 First parameter
Copy Rect r4; Point ctor: (0, 0) Point r4.TL
Constructor //Rect() Point ctor: (0, 0) Point r4.BR
Call by value Rect ctor: [(0, 0) (0, 0)] Rect r4
Signature return 0; Rect dtor: [(0, 0) (0, 0)] ˜Rect r4
Data members } Point dtor: (0, 0) ˜Point r4.BR
Free Copy Point dtor: (0, 0) ˜Point r4.TL
Constructor
Rect dtor: [(2, 2) (6, 4)] ˜Rect r3
Copy Point dtor: (6, 4) ˜Point r3.BR
Assignment Point dtor: (2, 2) ˜Point r3.TL
Operator Rect dtor: [(3, 5) (6, 9)] ˜Rect r2
Copy Pointer Point dtor: (6, 9) ˜Point r2.BR
Self-Copy Point dtor: (3, 5) ˜Point r2.TL
Signature Rect dtor: [(0, 2) (5, 7)] ˜Rect r1
Point dtor: (5, 7) ˜Point r1.BR
Summary NPTEL MOOCs Programming in C++ Point dtor: (0, 2) Partha ˜Point
Pratimr1.TL
Das 18
Free Copy Constructor

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 19


Program 14.09: Complex: Free Copy Constructor
#include <iostream>
Module 14 using namespace std;

Partha Pratim class Complex { double re_, im_; public:


Das Complex(double re, double im) : re_(re), im_(im) // Constructor
{ cout << "ctor: "; print(); }
//Complex(const Complex& c) : re_(c.re_), im_(c.im_) // Copy Constructor
Objectives &
//{ cout << "copy ctor: "; print(); }
Outline
~Complex() { cout << "dtor: "; print(); }
Lifetime double norm() { return sqrt(re_*re_ + im_*im_); }
Examples void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
};
String
void Display(Complex c_param) { cout << "Display: "; c_param.print(); }
Date
Rect
int main() {
Name & Address
Complex c(4.2, 5.3); // Constructor - Complex(double, double)
CreditCard
Display(c); // Free Copy Constructor called to copy c to c_param
Copy
Constructor return 0;
Call by value }
Signature User-defined CCtor Free CCtor
Data members ctor: |4.2+j5.3| = 6.7624 ctor: |4.2+j5.3| = 6.7624
Free Copy copy ctor: |4.2+j5.3| = 6.7624 \\ No message from free CCtor
Constructor Display: |4.2+j5.3| = 6.7624 Display: |4.2+j5.3| = 6.7624
dtor: |4.2+j5.3| = 6.7624 dtor: |4.2+j5.3| = 6.7624
Copy dtor: |4.2+j5.3| = 6.7624 dtor: |4.2+j5.3| = 6.7624
Assignment
Operator • User has provided no copy constructor
Copy Pointer • Compiler provides free copy constructor
Self-Copy • Compiler-provided copy constructor performs bit-copy - hence there is no message
Signature • Correct in this case as members are of built-in type
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 20
Program 14.11: String:
User-defined Copy Constructor
#include <iostream>
Module 14 #include <cstdlib>
#include <cstring>
Partha Pratim using namespace std;
Das class String { public: char *str_; size_t len_;
String(char *s) : str_(strdup(s)), len_(strlen(str_)) { } // ctor
String(const String& s) : str_(strdup(s.str_)), len_(s.len_) { } // cctor
Objectives &
~String() { free(str_); } // dtor
Outline
void print() { cout << "(" << str_ << ": " << len_ << ")" << endl; }
Lifetime };
Examples void strToUpper(String a) { // Make the string uppercase
for (int i = 0; i < a.len_; ++i) a.str_[i] = toupper(a.str_[i]);
String
cout << "strToUpper: "; a.print();
Date
Rect
}
Name & Address
int main() {
CreditCard String s = "Partha";
s.print();
Copy strToUpper(s);
Constructor s.print();
Call by value return 0;
Signature }
Data members ---
Free Copy (Partha: 6)
Constructor strToUpper: (PARTHA: 6)
Copy (Partha: 6)
Assignment
• User has provided copy constructor. So Compiler does not provide free copy constructor
Operator
• When actual parameter s is copied to formal parameter a, space is allocated for a.str and then it is
Copy Pointer copied from s.str . On exit from strToUpper, a is destructed and a.str is deallocated. But in main, s
Self-Copy
remains intact and access to s.str is valid.
Signature
• Deep Copy: While copying the object, the pointed object is copied in a fresh allocation. This is safe
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 21
Program 14.11: String:
Free Copy Constructor
#include <iostream>
Module 14 using namespace std;
class String { public: char *str_; size_t len_;
Partha Pratim String(char *s) : str_(strdup(s)), len_(strlen(str_)) { } // ctor
Das //String(const String& s) : str_(strdup(s.str_)), len_(s.len_) { } // cctor
~String() { free(str_); } // dtor
void print() { cout << "(" << str_ << ": " << len_ << ")" << endl; } };
Objectives &
void strToUpper(String a) { // Make the string uppercase
Outline
for (int i = 0; i < a.len_; ++i) a.str_[i] = toupper(a.str_[i]);
Lifetime cout << "strToUpper: "; a.print(); }
Examples int main() {
String s = "Partha";
String
Date
Rect s.print();
Name & Address strToUpper(s);
CreditCard s.print();

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 22


Program 14.12: Complex:
Copy Assignment
#include <iostream>
Module 14 #include <cmath>
using namespace std;
Partha Pratim class Complex { double re_, im_; public:
Das Complex(double re, double im) : re_(re), im_(im) { cout << "ctor: "; print(); }
Complex(const Complex& c) : re_(c.re_), im_(c.im_) { cout << "cctor: "; print(); }
~Complex() { cout << "dtor: "; print(); }
Objectives &
Complex& operator=(const Complex& c) // Copy Assignment Operator
Outline
{ re_ = c.re_; im_ = c.im_; cout << "copy: "; print(); return *this; }
Lifetime double norm() { return sqrt(re_*re_ + im_*im_); }
Examples void print() { cout << "|" << re_ << "+j" << im_ << "| = " << norm() << endl; }
};
String
int main() {
Date
Rect
Complex c1(4.2, 5.3), c2(7.9, 8.5); // Constructor - Complex(double, double)
Name & Address
Complex c3(c2); // Constructor - Complex(const Complex& c)
CreditCard
c1.print(); c2.print(); c3.print();
Copy c2 = c1; c2.print(); // Copy Assignment Operator
Constructor c1 = c2 = c3; c1.print(); c2.print(); c3.print(); // Copy Assignment Chain
Call by value return 0;
Signature }
Data members ctor: |4.2+j5.3| = 6.7624 // c1 - ctor copy: |7.9+j8.5| = 11.6043 // c2 <- c3
Free Copy ctor: |7.9+j8.5| = 11.6043 // c2 - ctor copy: |7.9+j8.5| = 11.6043 // c1 <- c2
Constructor cctor: |7.9+j8.5| = 11.6043 // c3 - ctor |7.9+j8.5| = 11.6043 // c1
|4.2+j5.3| = 6.7624 // c1 |7.9+j8.5| = 11.6043 // c2
Copy |7.9+j8.5| = 11.6043 // c2 |7.9+j8.5| = 11.6043 // c3
Assignment |7.9+j8.5| = 11.6043 // c3 dtor: |7.9+j8.5| = 11.6043 // c3 - dtor
Operator copy: |4.2+j5.3| = 6.7624 // c2 <- c1 dtor: |7.9+j8.5| = 11.6043 // c2 - dtor
Copy Pointer |4.2+j5.3| = 6.7624 // c2 dtor: |7.9+j8.5| = 11.6043 // c1 - dtor
Self-Copy
Signature • Copy assignment operator should return the object to make chain assignments possible
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 23
Program 14.13: String:
Copy Assignment
#include <iostream>
Module 14 #include <cstdlib>
#include <cstring>
Partha Pratim using namespace std;
Das
class String { public: char *str_; size_t len_;
String(char *s) : str_(strdup(s)), len_(strlen(str_)) { } // ctor
Objectives &
String(const String& s) : str_(strdup(s.str_)), len_(s.len_) { } // cctor
Outline
~String() { free(str_); } // dtor
Lifetime String& operator=(const String& s) {
Examples free(str_); // Release existing memory
str_ = strdup(s.str_); // Perform deep copy
String
len_ = s.len_;
Date
Rect
return *this; // Return object for chain assignment
Name & Address
}
CreditCard void print() { cout << "(" << str_ << ": " << len_ << ")" << endl; }
};
Copy int main() { String s1 = "Football", s2 = "Cricket";
Constructor s1.print(); s2.print();
Call by value s2 = s1; s2.print();
Signature return 0;
Data members }
Free Copy ---
Constructor (Football: 8)
Copy (Cricket: 7)
Assignment (Football: 8)
Operator
• In copy assignment operator, str = s.str should not be done for two reasons:
Copy Pointer 1) Resource held by str will leak
Self-Copy
2) Shallow copy will result with its related issues
Signature
• What happens if a self-copy s1 = s1 is done?
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 24
Program 14.13: String:
Self Copy
#include <iostream>
Module 14 #include <cstdlib>
#include <cstring>
Partha Pratim using namespace std;
Das
class String { public: char *str_; size_t len_;
String(char *s) : str_(strdup(s)), len_(strlen(str_)) { } // ctor
Objectives &
String(const String& s) : str_(strdup(s.str_)), len_(s.len_) { } // cctor
Outline
~String() { free(str_); } // dtor
Lifetime String& operator=(const String& s) {
Examples free(str_); // Release existing memory
str_ = strdup(s.str_); // Perform deep copy
String
len_ = s.len_;
Date
Rect
return *this; // Return object for chain assignment
Name & Address
}
CreditCard void print() { cout << "(" << str_ << ": " << len_ << ")" << endl; }
};
Copy int main() { String s1 = "Football", s2 = "Cricket";
Constructor s1.print(); s2.print();
Call by value s1 = s1; s1.print();
Signature return 0;
Data members }
Free Copy ---
Constructor (Football: 8)
Copy (Cricket: 7)
Assignment (????????: 8) // Garbage is printed
Operator
• For self-copy str and s.str are the same pointers
Copy Pointer
• Hence, free(str ) first releases the memory, and then strdup(s.str ) tries to copy from released memory
Self-Copy
• This may crash or produce garbage values
Signature
• Self-copy must be detected and protected
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 25
Program 14.14: String:
Self Copy – Safe
#include <iostream>
Module 14 #include <cstdlib>
#include <cstring>
Partha Pratim using namespace std;
Das
class String { public: char *str_; size_t len_;
String(char *s) : str_(strdup(s)), len_(strlen(str_)) { } // ctor
Objectives &
String(const String& s) : str_(strdup(s.str_)), len_(s.len_) { } // cctor
Outline
~String() { free(str_); } // dtor
Lifetime String& operator=(const String& s) {
Examples if (this != &s) {
free(str_);
String
str_ = strdup(s.str_);
Date
Rect
len_ = s.len_;
Name & Address
}
CreditCard return *this;
}
Copy void print() { cout << "(" << str_ << ": " << len_ << ")" << endl; }
Constructor };
Call by value int main() { String s1 = "Football", s2 = "Cricket";
Signature s1.print(); s2.print();
Data members s1 = s1; s1.print();
Free Copy return 0;
Constructor }
Copy ---
Assignment (Football: 8)
Operator (Cricket: 7)
Copy Pointer
(Football: 8)
Self-Copy
• Check for self-copy (this != &s)
Signature
• In case of self-copy, do nothing
Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 26
Signature and Body of
Copy Assignment Operator
Module 14 For class MyClass, typical copy assignment operator will be:
Partha Pratim MyClass& operator=(const MyClass& s) {
Das if (this != &s) {
// Release resources held by *this
Objectives & // Copy members of s to members of *this
Outline }
return *this;
Lifetime }
Examples
String Signature of a Copy Assignment Operator can be one of:
Date
Rect
Name & Address MyClass& operator=(const MyClass& rhs); // Common
CreditCard // No change in Source
MyClass& operator=(MyClass& rhs); // Occasional
Copy // Change in Source
Constructor
Call by value
Signature
The following Copy Assignment Operators are occasionally used:
Data members
Free Copy MyClass& operator=(MyClass rhs);
Constructor const MyClass& operator=(const MyClass& rhs);
Copy const MyClass& operator=(MyClass& rhs);
Assignment const MyClass& operator=(MyClass rhs);
Operator MyClass operator=(const MyClass& rhs);
MyClass operator=(MyClass& rhs);
Copy Pointer
MyClass operator=(MyClass rhs);
Self-Copy
Signature

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 27


Module Summary

Module 14

Partha Pratim Copy Constructors


Das
A new object is created
Objectives & The new object is initialized with the value of data
Outline
members of another object
Lifetime
Examples Copy Assignment Operator
String
Date An object is already existing (and initialized)
Rect
Name & Address
The members of the existing object are replaced by values
CreditCard
of data members of another object
Copy
Constructor Deep and Shallow Copy for Pointer Members
Call by value
Signature Deep copy allocates new space for the contents and copies
Data members
Free Copy
the pointed data
Constructor
Shallow copy merely copies the pointer value – hence, the
Copy
Assignment new copy and the original pointer continue to point to the
Operator
Copy Pointer
same data
Self-Copy
Signature

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 28


Instructor and TAs

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

Summary NPTEL MOOCs Programming in C++ Partha Pratim Das 29


Module 15

Partha Pratim
Das
Module 15: Programming in C++
Objectives &
Outline
Const-ness
Constant
Objects

Constant Partha Pratim Das


Member
Functions

Constant Data
Department of Computer Science and Engineering
Members Indian Institute of Technology, Kharagpur
Credit Card
Example [email protected]
mutable
Members

Summary Tanwi Mallick


Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 15

Partha Pratim Understand const-ness of objects in C++


Das
Understand the use of const-ness in class design
Objectives &
Outline

Constant
Objects

Constant
Member
Functions

Constant Data
Members
Credit Card
Example

mutable
Members

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 15

Partha Pratim Constant Objects


Das
Constant Member methods
Objectives &
Outline Constant Data members
Constant Credit Card Example
Objects

Constant mutable Data members - logical and bitwise const-ness


Member
Functions

Constant Data
Members
Credit Card
Example

mutable
Members

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Constant Objects

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 // Const Pointer to non-Const Object


Members MyClass * const this;
Credit Card
Example

mutable as for a non-constant object of the same class


Members
A constant objects cannot invoke normal methods of the class lest these
Summary methods change the object
Let us take an example

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Program 15.01: Example: Non-Constant Objects
#include <iostream>
Module 15 using namespace std;

Partha Pratim class MyClass {


Das int myPriMember_;
public:
int myPubMember_;
Objectives &
MyClass(int mPri, int mPub) : myPriMember_(mPri), myPubMember_(mPub) {}
Outline
int getMember() { return myPriMember_; }
Constant void setMember(int i) { myPriMember_ = i; }
Objects void print() { cout << myPriMember_ << ", " << myPubMember_ << endl; }
};
Constant int main() {
Member MyClass myObj(0, 1); // Non-constant object
Functions
cout << myObj.getMember() << endl;
Constant Data myObj.setMember(2);
Members myObj.myPubMember_ = 3;
Credit Card myObj.print();
Example
return 0;
mutable
}
Members
---
Summary 0
2, 3

• It is okay to invoke methods for non-constant object myObj


• It is okay to make changes in non-constant object myObj by method (setMember())
• It is okay to make changes in non-constant object myObj directly (myPubMember )

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Program 15.02: Example: Constant Objects
#include <iostream>
Module 15 using namespace std;

Partha Pratim class MyClass {


Das int myPriMember_;
public:
int myPubMember_;
Objectives &
MyClass(int mPri, int mPub) : myPriMember_(mPri), myPubMember_(mPub) {}
Outline
int getMember() { return myPriMember_; }
Constant void setMember(int i) { myPriMember_ = i; }
Objects void print() { cout << myPriMember_ << ", " << myPubMember_ << endl; }
};
Constant int main() {
Member const MyClass myConstObj(5, 6); // Constant object
Functions
cout << myConstObj.getMember() << endl; // Error 1
Constant Data myConstObj.setMember(7); // Error 2
Members myConstObj.myPubMember_ = 8; // Error 3
Credit Card myConstObj.print(); // Error 4
Example
return 0;
mutable
}
Members
• It is not allowed to invoke methods or make changes in constant object myConstObj
Summary
• Error (1, 2 & 4) on method invocation typically is:
cannot convert ’this’ pointer from ’const MyClass’ to ’MyClass &’
• Error (3) on member update typically is:
’myConstObj’ : you cannot assign to a variable that is const
• With const, this pointer is const MyClass * const while the methods expects MyClass * const
• Consequently, we cannot print the data member of the class (even without changing it)
• Fortunately, constant objects can invoke (select) methods if they are constant member functions
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Constant Member Function

To declare a constant member function, we use the keyword const between


Module 15
the function header and the body. Like:
Partha Pratim
Das
void print() const { cout << myMember_ << endl; }
Objectives &
Outline A constant member function expects a this pointer as:
Constant const MyClass * const this;
Objects
and hence can be invoked by constant objects
Constant
Member In a constant member function no data member can be changed. Hence,
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;

Partha Pratim class MyClass {


Das int myPriMember_;
public:
int myPubMember_;
Objectives &
MyClass(int mPri, int mPub) : myPriMember_(mPri), myPubMember_(mPub) {}
Outline
int getMember() const { return myPriMember_; }
Constant void setMember(int i) { myPriMember_ = i; }
Objects void print() const { cout << myPriMember_ << ", " << myPubMember_ << endl; }
};
Constant int main() {
Member MyClass myObj(0, 1); // Non-constant object
Functions const MyClass myConstObj(5, 6); // Constant object

Constant Data cout << myObj.getMember() << endl;


Members myObj.setMember(2);
Credit Card myObj.myPubMember_ = 3;
Example myObj.print();
mutable Output
cout << myConstObj.getMember() << endl;
Members 0
//myConstObj.setMember(7);
//myConstObj.myPubMember_ = 8; 2, 3
Summary
myConstObj.print(); 5
return 0; 5, 6
}

• 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

mutable A constant data member cannot be changed even in a non-constant


Members object
Summary A constant data member must be initialized on the initialization list

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Program 15.04: Example: Constant Data Member
#include <iostream>
Module 15 using namespace std;
class MyClass {
Partha Pratim const int cPriMem_;
Das int priMem_;
public:
const int cPubMem_;
Objectives &
int pubMem_;
Outline
MyClass(int cPri, int ncPri, int cPub, int ncPub) :
Constant cPriMem_(cPri), priMem_(ncPri), cPubMem_(cPub), pubMem_(ncPub) {}
Objects int getcPri() { return cPriMem_; }
void setcPri(int i) { cPriMem_ = i; } // Error 1: Assignment to constant data member
Constant int getPri() { return priMem_; }
Member void setPri(int i) { priMem_ = i; }
Functions };
int main() {
Constant Data MyClass myObj(1, 2, 3, 4);
Members
Credit Card cout << myObj.getcPri() << endl; myObj.setcPri(6);
Example cout << myObj.getPri() << endl; myObj.setPri(6);
mutable
cout << myObj.cPubMem_ << endl;
Members
myObj.cPubMem_ = 3; // Error 2: Assignment to constant data member
Summary
cout << myObj.pubMem_ << endl; myObj.pubMem_ = 3;
return 0;
}

• It is not allowed to make changes to constant data members in myObj


• Error 1:l-value specifies const object
• Error 2:’myObj’ : you cannot assign to a variable that is const
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Credit Card 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Program 15.05: String Class:
In header file with copy
#ifndef __STRING_H
Module 15 #define __STRING_H
#include <iostream>
Partha Pratim #include <cstring>
Das using namespace std;

class String { char *str_; size_t len_;


Objectives &
public:
Outline
String(const char *s) : str_(strdup(s)), len_(strlen(str_)) // ctor
Constant { cout << "String ctor: "; print(); cout << endl; }
Objects String(const String& s) : str_(strdup(s.str_)), len_(strlen(str_)) // cctor
{ cout << "String cctor: "; print(); cout << endl; }
Constant String& operator=(const String& s) {
Member if (this != &s) {
Functions free(str_);
str_ = strdup(s.str_);
Constant Data len_ = s.len_;
Members }
Credit Card return *this;
Example }
~String() { cout << "String dtor: "; print(); cout << endl; free(str_); } // dtor
mutable
void print() const { cout << str_; }
Members
};
Summary #endif // __STRING_H

• Copy Constructor and Copy Assignment Operator added


• print() made a constant member function

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Program 15.05: Date Class:
In header file with copy
#ifndef __DATE_H
Module 15 #define __DATE_H
#include <iostream>
Partha Pratim using namespace std;
Das
char monthNames[][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
Objectives &
char dayNames[][10] = { "Monday", "Tuesday", "Wednesday", "Thursday",
Outline
"Friday", "Saturday", "Sunday" };
Constant class Date {
Objects enum Month { Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
enum Day { Mon, Tue, Wed, Thr, Fri, Sat, Sun };
Constant typedef unsigned int UINT;
Member UINT date_; Month month_; UINT year_;
Functions public:
Date(UINT d, UINT m, UINT y) : date_(d), month_((Month)m), year_(y)
Constant Data { cout << "Date ctor: "; print(); cout << endl; }
Members Date(const Date& d) : date_(d.date_), month_(d.month_), year_(d.year_)
Credit Card { cout << "Date cctor: "; print(); cout << endl; }
Example Date& operator=(const Date& d) { date_ = d.date_; month_ = d.month_; year_ = d.year_;
return *this;
mutable
}
Members
~Date() { cout << "Date dtor: "; print(); cout << endl; }
Summary void print() const { cout << date_ << "/" << monthNames[month_ - 1] << "/" << year_; }
bool validDate() const { /* Check validity */ return true; } // Not Implemented (NI)
Day day() const { /* Compute day from date using time.h */ return Mon; } // NI
};
#endif // __DATE_H

• Copy Constructor and Copy Assignment Operator added


• print(), validDate(), and day() made constant member functions
NPTEL MOOCs Programming in C++ Partha Pratim Das 13
Program 15.05: Name Class:
In header file with copy
#ifndef __NAME_H
Module 15 #define __NAME_H
#include <iostream>
Partha Pratim using namespace std;
Das
#include "String.h"
Objectives &
class Name {
Outline
String firstName_, lastName_;
Constant public:
Objects Name(const char* fn, const char* ln) : firstName_(fn), lastName_(ln)
{ cout << "Name ctor: "; print(); cout << endl; }
Constant Name(const Name& n) : firstName_(n.firstName_), lastName_(n.firstName_)
Member { cout << "Name cctor: "; print(); cout << endl; }
Functions Name& operator=(const Name& n) {
firstName_ = n.firstName_;
Constant Data lastName_ = n.lastName_;
Members return *this;
Credit Card }
Example ~Name() { cout << "Name dtor: "; print(); cout << endl; }
void print() const
mutable
{ firstName_.print(); cout << " "; lastName_.print(); }
Members
};
Summary #endif // __NAME_H

• Copy Constructor and Copy Assignment Operator added


• print() made a constant member function

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Program 15.05: Address Class:
In header file with copy
#ifndef __ADDRESS_H
Module 15 #define __ADDRESS_H
#include <iostream>
Partha Pratim using namespace std;
Das
#include "String.h"
Objectives &
class Address {
Outline
unsigned int houseNo_;
Constant String street_, city_, pin_;
Objects public:
Address(unsigned int hn, const char* sn, const char* cn, const char* pin) :
Constant houseNo_(hn), street_(sn), city_(cn), pin_(pin)
Member { cout << "Address ctor: "; print(); cout << endl; }
Functions Address(const Address& a) :
houseNo_(a.houseNo_), street_(a.street_), city_(a.city_), pin_(a.pin_)
Constant Data { cout << "Address cctor: "; print(); cout << endl; }
Members Address& operator=(const Address& a) {
Credit Card houseNo_ = a.houseNo_; street_ = a.street_; city_ = a.city_; pin_ = a.pin_;
Example return *this;
}
mutable
~Address() { cout << "Address dtor: "; print(); cout << endl; }
Members
void print() const {
Summary cout << houseNo_ << " "; street_.print(); cout << " ";
city_.print(); cout << " "; pin_.print();
}
};
#endif // __ADDRESS_H

• Copy Constructor and Copy Assignment Operator added


• print() made a constant member function
NPTEL MOOCs Programming in C++ Partha Pratim Das 15
Program 15.05: Credit Card Class:
In header file with edit options
#ifndef __CREDIT_CARD_H
Module 15 #define __CREDIT_CARD_H
#include <iostream>
Partha Pratim using namespace std;
Das #include "Date.h"
#include "Name.h"
#include "Address.h"
Objectives &
class CreditCard { typedef unsigned int UINT; char *cardNumber_;
Outline
Name holder_; Address addr_; Date issueDate_, expiryDate_; UINT cvv_;
Constant public:
Objects CreditCard(const char* cNumber, const char* fn, const char* ln,
unsigned int hn, const char* sn, const char* cn, const char* pin,
Constant UINT issueMonth, UINT issueYear, UINT expiryMonth, UINT expiryYear, UINT cvv) :
Member holder_(fn, ln), addr_(hn, sn, cn, pin), issueDate_(1, issueMonth, issueYear),
Functions expiryDate_(1, expiryMonth, expiryYear), cvv_(cvv)
{ cardNumber_ = new char[strlen(cNumber) + 1]; strcpy(cardNumber_, cNumber);
Constant Data cout << "CC ctor: "; print(); cout << endl; }
Members ~CreditCard() { cout << "CC dtor: "; print(); cout << endl; }
Credit Card
Example void setHolder(const Name& h) { holder_ = h; } // Change holder name
void setAddress(const Address& a) { addr_ = a; } // Change address
mutable
void setIssueDate(const Date& d) { issueDate_ = d; } // Change issue date
Members
void setExpiryDate(const Date& d) { expiryDate_ = d; } // Change expiry date
Summary void setCVV(UINT v) { cvv_ = v; } // Change cvv number
void print() const { cout<<cardNumber_<<" "; holder_.print(); cout<<" "; addr_.print();
cout<<" "; issueDate_.print(); cout<<" "; expiryDate_.print(); cout<<" "; cout<<cvv_;
};
#endif // __CREDIT_CARD_H

• Set methods added


• print() made a constant member function
NPTEL MOOCs Programming in C++ Partha Pratim Das 16
Program 15.05: Credit Card Class Application
#include <iostream>
Module 15 using namespace std;

Partha Pratim #include "CreditCard.h"


Das
int main() {
CreditCard cc("5321711934640027", "Sharlock", "Holmes",
Objectives &
221, "Baker Street", "London", "NW1 6XE", 7, 2014, 6, 2016, 811);
Outline
cout << endl; cc.print(); cout << endl << endl;;
Constant
Objects cc.setHolder(Name("David", "Cameron"));
cc.setAddress(Address(10, "Downing Street", "London", "SW1A 2AA"));
Constant cc.setIssueDate(Date(1, 7, 2017));
Member cc.setExpiryDate(Date(1, 6, 2019));
Functions cc.setCVV(127);
cout << endl; cc.print(); cout << endl << endl;;
Constant Data
Members return 0;
Credit Card }
Example // Construction of Data Members & Object
mutable
Members 5321711934640027 Sharlock Holmes 221 Baker Street London NW1 6XE 1/Jul/2014 1/Jun/2016 811

Summary // Construction & Destruction of temporary objects

5321711934640027 David Cameron 10 Downing Street London SW1A 2AA 1/Jul/2017 1/Jun/2019 127

// Destruction of Data Members & Object


• We could change address, issue date, expiry date, and cvv. This is fine
• We could change the name of the holder! This should not be allowed
NPTEL MOOCs Programming in C++ Partha Pratim Das 17
Program 15.06: Credit Card Class:
Constant data members
#ifndef __CREDIT_CARD_H
Module 15 #define __CREDIT_CARD_H
// Include <iostream>, "String.h", "Date.h", "Name.h", "Address.h"
Partha Pratim using namespace std;
Das
class CreditCard { typedef unsigned int UINT;
char *cardNumber_;
Objectives &
const Name holder_; // Holder name cannot be changed after construction
Outline
Address addr_;
Constant Date issueDate_, expiryDate_; UINT cvv_;
Objects public:
CreditCard(...) : ... { ... }
Constant ~CreditCard() { ... }
Member
Functions void setHolder(const Name& h) { holder_ = h; } // Change holder name
// error C2678: binary ’=’ : no operator found which takes a left-hand operand
Constant Data // of type ’const Name’ (or there is no acceptable conversion)
Members
Credit Card void setAddress(const Address& a) { addr_ = a; } // Change address
Example void setIssueDate(const Date& d) { issueDate_ = d; } // Change issue date
void setExpiryDate(const Date& d) { expiryDate_ = d; } // Change expiry date
mutable
void setCVV(UINT v) { cvv_ = v; } // Change cvv number
Members

Summary void print() { ... }


};
#endif // __CREDIT_CARD_H

• 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 18


Program 15.06: Credit Card Class:
Clean
#ifndef __CREDIT_CARD_H
Module 15 #define __CREDIT_CARD_H
// Include <iostream>, "String.h", "Date.h", "Name.h", "Address.h"
Partha Pratim using namespace std;
Das
class CreditCard { typedef unsigned int UINT;
char *cardNumber_;
Objectives &
const Name holder_; // Holder name cannot be changed after construction
Outline
Address addr_;
Constant Date issueDate_, expiryDate_; UINT cvv_;
Objects public:
CreditCard(...) : ... { ... }
Constant ~CreditCard() { ... }
Member
Functions void setAddress(const Address& a) { addr_ = a; } // Change address
void setIssueDate(const Date& d) { issueDate_ = d; } // Change issue date
Constant Data void setExpiryDate(const Date& d) { expiryDate_ = d; } // Change expiry date
Members void setCVV(UINT v) { cvv_ = v; } // Change cvv number
Credit Card
Example void print() { ... }
};
mutable
#endif // __CREDIT_CARD_H
Members
• Method setHolder() removed
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 19


Program 15.06: Credit Card Class Application:
Revised
#include <iostream>
Module 15 using namespace std;

Partha Pratim #include "CreditCard.h"


Das
int main() {
CreditCard cc("5321711934640027", "Sharlock", "Holmes",
Objectives &
221, "Baker Street", "London", "NW1 6XE", 7, 2014, 6, 2016, 811);
Outline
cout << endl; cc.print(); cout << endl << endl;;
Constant
Objects // cc.setHolder(Name("David", "Cameron"));
cc.setAddress(Address(10, "Downing Street", "London", "SW1A 2AA"));
Constant cc.setIssueDate(Date(1, 7, 2017));
Member cc.setExpiryDate(Date(1, 6, 2019));
Functions cc.setCVV(127);
cout << endl; cc.print(); cout << endl << endl;;
Constant Data
Members return 0;
Credit Card }
Example // Construction of Data Members & Object
mutable
Members 5321711934640027 Sharlock Holmes 221 Baker Street London NW1 6XE 1/Jul/2014 1/Jun/2016 811

Summary // Construction & Destruction of temporary objects

5321711934640027 Sharlock Holmes 10 Downing Street London SW1A 2AA 1/Jul/2017 1/Jun/2019 127

// Destruction of Data Members & Object


• Now holder cannot be changed. So we are safe
• However, it is still possible to replace or edit the card number. This, too, should be disallowed
NPTEL MOOCs Programming in C++ Partha Pratim Das 20
Program 15.07: Credit Card Class:
cardMember Issue
#ifndef __CREDIT_CARD_H
Module 15 #define __CREDIT_CARD_H
// Include <iostream>, "String.h", "Date.h", "Name.h", "Address.h"
Partha Pratim using namespace std;
Das
class CreditCard { typedef unsigned int UINT;
char *cardNumber_; // Card number is editable as well as replaceable
Objectives &
const Name holder_; // Holder name cannot be changed after construction
Outline
Address addr_;
Constant Date issueDate_, expiryDate_; UINT cvv_;
Objects public:
CreditCard(...) : ... { ... }
Constant ~CreditCard() { ... }
Member
Functions void setAddress(const Address& a) { addr_ = a; } // Change address
void setIssueDate(const Date& d) { issueDate_ = d; } // Change issue date
Constant Data void setExpiryDate(const Date& d) { expiryDate_ = d; } // Change expiry date
Members void setCVV(UINT v) { cvv_ = v; } // Change cvv number
Credit Card
Example void print() { ... }
};
mutable
#endif // __CREDIT_CARD_H
Members
• It is still possible to replace or edit the card number
Summary
• To make the cardNumber non-replaceable, we need to make this pointer constant
• Further, to make it non-editable we need to make cardNumber point to a constant string
• Hence, we change char *cardNumber to const char * const cardNumber

NPTEL MOOCs Programming in C++ Partha Pratim Das 21


Program 15.07: Credit Card Class:
cardMember Issue
#ifndef __CREDIT_CARD_H
Module 15 #define __CREDIT_CARD_H
// Include <iostream>, "String.h", "Date.h", "Name.h", "Address.h"
Partha Pratim using namespace std;
Das class CreditCard {
typedef unsigned int UINT;
const char * const cardNumber_; // Card number cannot be changed after construction
Objectives &
const Name holder_; // Holder name cannot be changed after construction
Outline
Address addr_; Date issueDate_, expiryDate_; UINT cvv_;
Constant public:
Objects CreditCard(const char* cNumber, const char* fn, const char* ln,
unsigned int hn, const char* sn, const char* cn, const char* pin,
Constant UINT issueMonth, UINT issueYear, UINT expiryMonth, UINT expiryYear, UINT cvv) :
Member holder_(fn, ln), addr_(hn, sn, cn, pin), issueDate_(1, issueMonth, issueYear),
Functions expiryDate_(1, expiryMonth, expiryYear), cvv_(cvv)
{
Constant Data cardNumber_ = new char[strlen(cNumber) + 1]; // ERROR: No assignment to const pointer
Members strcpy(cardNumber_, cNumber); // ERROR: No copy to const C-string
Credit Card cout << "CC ctor: "; print(); cout << endl;
Example }
~CreditCard() { cout << "CC dtor: "; print(); cout << endl; }
mutable
Members
// Set methods and print method skipped ...
Summary };
#endif // __CREDIT_CARD_H

• cardNumber is now a constant pointer to a constant string


• With this the allocation for the C-string fails in the body as constant pointer cannot be assigned
• Further, copy of C-string (strcpy() fails as copy of constant C-string is not allowed
• We need to move these codes to the initialization list

NPTEL MOOCs Programming in C++ Partha Pratim Das 22


Program 15.07: Credit Card Class:
cardMember Issue Resolved
#include <iostream>
Module 15 using namespace std;
#include "String.h"
Partha Pratim #include "Date.h"
Das #include "Name.h"
#include "Address.h"
class CreditCard {
Objectives &
typedef unsigned int UINT;
Outline
const char * const cardNumber_; // Card number cannot be changed after construction
Constant const Name holder_; // Holder name cannot be changed after construction
Objects Address addr_; Date issueDate_, expiryDate_; UINT cvv_;
public:
Constant CreditCard(const char* cNumber, const char* fn, const char* ln,
Member unsigned int hn, const char* sn, const char* cn, const char* pin,
Functions UINT issueMonth, UINT issueYear, UINT expiryMonth, UINT expiryYear, UINT cvv) :
cardNumber_(strcpy(new char[strlen(cNumber)+1], cNumber)),
Constant Data holder_(fn, ln), addr_(hn, sn, cn, pin), issueDate_(1, issueMonth, issueYear),
Members expiryDate_(1, expiryMonth, expiryYear), cvv_(cvv)
Credit Card { cout << "CC ctor: "; print(); cout << endl; }
Example ~CreditCard() { cout << "CC dtor: "; print(); cout << endl; }
void setAddress(const Address& a) { addr_ = a; } // Change address
mutable
void setIssueDate(const Date& d) { issueDate_ = d; } // Change issue date
Members
void setExpiryDate(const Date& d) { expiryDate_ = d; } // Change expiry date
Summary void setCVV(UINT v) { cvv_ = v; } // Change cvv number
void print() { cout<<cardNumber_<<" "; holder_.print(); cout<<" "; addr_.print();
cout<<" "; issueDate_.print(); cout<<" "; expiryDate_.print(); cout<<" "; cout<<cvv_;
};

• Note the initialization of cardNumber in initialization list


• All constant data members must be initialized in initialization list

NPTEL MOOCs Programming in C++ Partha Pratim Das 23


mutable Data Members

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 24


Program 15.08: mutable Data Members

Module 15 #include <iostream>


using namespace std;
class MyClass {
Partha Pratim
int mem_;
Das
mutable int mutableMem_;
public:
Objectives & MyClass(int m, int mm) : mem_(m), mutableMem_(mm) {}
Outline int getMem() const { return mem_; }
void setMem(int i) { mem_ = i; }
Constant int getMutableMem() const { return mutableMem_; }
Objects void setMutableMem(int i) const { mutableMem_ = i; } // Okay to change mutable
};
Constant int main() {
Member const MyClass myConstObj(1, 2);
Functions
cout << myConstObj.getMem() << endl;
Constant Data
//myConstObj.setMem(3); // Error to invoke
Members
Credit Card cout << myConstObj.getMutableMem() << endl;
Example
myConstObj.setMutableMem(4);
mutable
Members return 0;
}
Summary
• setMutableMem() is a constant member function so that constant myConstObj can invoke it
• setMutableMem() can still set mutableMem because mutableMem is mutable
• In contrast, myConstObj cannot invoke setMem() and hence mem cannot be changed

NPTEL MOOCs Programming in C++ Partha Pratim Das 25


Logical vis-a-vis Bit-wise Const-ness

Module 15 const in C++, models bit-wise constant. Once an object


Partha Pratim is declared const, no part (actually, no bit) of it can be
Das
changed after construction (and initialization)
Objectives &
Outline However, while programming we often need an object to
Constant be logically constant. That is, the concept represented by
Objects
the object should be constant; but if its representation
Constant
Member need more data members for computation and modeling,
Functions
these have no reason to be constant.
Constant Data
Members mutable allows such surrogate data members to be
Credit Card
Example
changeable in a (bit-wise) constant object to model
mutable
Members logically const objects
Summary To use mutable we shall look for:
A logically constant concept
A need for data members outside the representation of the
concept; but are needed for computation
NPTEL MOOCs Programming in C++ Partha Pratim Das 26
Program 15.09:
When to use mutable Data Members?
• Typically, when a class represents a constant concept, and
Module 15 • It computes a value first time and caches the result for future use

Partha Pratim // Source: http://www.highprogrammer.com/alan/rants/mutable.html


Das
#include <iostream>
using namespace std;
Objectives &
class MathObject { // Constant concept of PI
Outline
mutable bool piCached_; // Needed for computation
Constant mutable double pi_; // Needed for computation
Objects public:
MathObject() : piCached_(false) { } // Not available at construction
Constant double pi() const { // Can access PI only through this method
Member if (!piCached_) { // An insanely slow way to calculate pi
Functions pi_ = 4;
for (long step = 3; step < 1000000000; step += 4) {
Constant Data pi_ += ((-4.0 / (double)step) + (4.0 / ((double)step + 2)));
Members }
Credit Card piCached_ = true; // Now computed and cached
Example }
mutable return pi_;
Members }
};
Summary int main() {
const MathObject mo;
cout << mo.pi() << endl; // Access PI
return 0;
}

• Here a MathObject is logically constant; but we use mutable members for computation

NPTEL MOOCs Programming in C++ Partha Pratim Das 27


Program 15.10:
When not to use mutable Data Members?
• mutable should be rarely used – only when it is really needed. A bad example follows:
Module 15
Improper Design (mutable) Proper Design (const)
Partha Pratim
Das class Employee { class Employee {
string _name; const string _name;
string _id; const string _id;
Objectives &
mutable double _salary; double _salary;
Outline
public: public:
Constant Employee(string name = "No Name", Employee(string name = "No Name",
Objects string id = "000-00-0000", string id = "000-00-0000",
double salary = 0) double salary = 0)
Constant : _name(name), _id(id) : _name(name), _id(id)
Member { _salary = salary; } { _salary = salary; }
Functions string getName() const; string getName() const;
void setName(string name);
Constant Data string getid() const; string getid() const;
Members void setid(string id);
Credit Card double getSalary() const; double getSalary() const;
Example void setSalary(double salary); void setSalary(double salary);
mutable void promote(double salary) const void promote(double salary)
Members {_salary = salary;} {_salary = salary;}
}; };
Summary --- ---
const Employee john("JOHN","007",5000.0); Employee john("JOHN","007",5000.0);
// ... // ...
john.promote(20000.0); john.promote(20000.0);

• Employee is not logically constant. If it is, then salary should also be const
• Design on right makes that explicit

NPTEL MOOCs Programming in C++ Partha Pratim Das 28


Module Summary

Module 15 Studied const-ness in C++


Partha Pratim In C++, there are three forms of const-ness
Das
Constant Objects:
Objectives & No change is allowed after construction
Outline
Cannot invoke normal member functions
Constant
Objects Constant Member Functions:
Constant Can be invoked by constant (as well as non-constant)
Member
Functions
objects
Cannot make changes to the object
Constant Data
Members Constant Data Members:
Credit Card
Example No change is allowed after construction
mutable Must be initialized in the initialization list
Members

Summary Further, learnt how to model logical const-ness over


bit-wise const-ness by proper use of mutable members

NPTEL MOOCs Programming in C++ Partha Pratim Das 29


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 30


Module 16

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 16

Partha Pratim Understand static data member and member function


Das

Objectives &
Outline

static data
member
Print Task

static
Member
function
Print Task

Singleton
Class

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 16

Partha Pratim static data member


Das
Print Task
Objectives &
Outline
static member function
static data
Print Task
member
Print Task Singleton Class
static
Member
function
Print Task

Singleton
Class

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


static Data Member
A static data member
Module 16
is associated with class not with object
Partha Pratim is shared by all the objects of a class
Das
needs to be defined outside the class scope (in addition to the declaration
Objectives & within the class scope) to avoid linker error
Outline
must be initialized in a source file
static data
member is constructed before main() starts and destructed after main() ends
Print Task
can be private / public type
static
Member can be accessed
function
Print Task
with the class-name followed by the scope resolution operator (::)
Singleton
as a member of any object of the class
Class virtually eliminates any need for global variables in OOPs environment
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Program 16.01: static Data Member
A Simple Case
Non static Data Member static Data Member
Module 16 #include<iostream> #include<iostream>
using namespace std; using namespace std;
Partha Pratim class MyClass { int x; // Non-static class MyClass { static int x; // Declare static
Das public: public:
void get() { x = 15; } void get() { x = 15; }
void print() { void print() {
Objectives &
x = x + 10; x = x + 10;
Outline
cout << "x =" << x << endl ; cout << "x =" << x << endl;
static data } }
member }; };
int MyClass::x = 0; // Define static data member
Print Task
int main() { int main() {
static MyClass obj1, obj2; MyClass obj1, obj2;
Member obj1.get(); obj2.get(); obj1.get(); obj2.get();
function
Print Task obj1.print(); obj2.print(); obj1.print(); obj2.print();
return 0 ; return 0;
Singleton } }
Class --- ---
x = 25 , x = 25 x = 25 , x = 35
Summary
• x is a non-static data member • x is static data member
• x cannot be shared between obj1 & obj2 • x is shared by all MyClass objects including
obj1 & obj2
• Non-static data members do not need sepa- • static data members must be defined in the
rate definitions - instantiated with the object global scope
• Non-static data members are initialized dur- • static data members are initialized during
ing object construction program start-up

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Program 16.02: static Data Member
Print Task
#include <iostream>
Module 16 using namespace std;
class PrintJobs { int nPages_; // # of pages in current job
public:
Partha Pratim
static int nTrayPages_; // # of pages remaining in the tray
Das
static int nJobs_; // # of print jobs executing
PrintJobs(int nP): nPages_(nP) {
Objectives & ++nJobs_;
Outline cout << "Printing " << nP << " pages" << endl;
nTrayPages_ = nTrayPages_ - nP;
static data }
member ~PrintJobs() { --nJobs_; }
Print Task };
int PrintJobs::nTrayPages_ = 500; // Definition and initialization -- load paper
static
int PrintJobs::nJobs_ = 0; // Definition and initialization -- no job to start with
Member
int main() {
function Output:
cout << "Jobs = " << PrintJobs::nJobs_ << endl;
Print Task cout << "Pages= " << PrintJobs::nTrayPages_ << endl;
Jobs = 0
Singleton PrintJobs job1(10);
Pages= 500
Class cout << "Jobs = " << PrintJobs::nJobs_ << endl;
Printing 10 pages
cout << "Pages= " << PrintJobs::nTrayPages_ << endl;
Jobs = 1
Summary {
Pages= 490
PrintJobs job1(30), job2(20);
Printing 30 pages
cout << "Jobs = " << PrintJobs::nJobs_ << endl;
Printing 20 pages
cout << "Pages= " << PrintJobs::nTrayPages_ << endl;
Jobs = 3
PrintJobs::nTrayPages_ += 100; // Load 100 more pages
Pages= 440
}
Jobs = 1
cout << "Jobs = " << PrintJobs::nJobs_ << endl;
Pages= 540
cout << "Pages= " << PrintJobs::nTrayPages_ << endl;
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
static Member Function

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Program 16.03: static Data & Member Function
Print Task (safe)
#include <iostream>
Module 16 using namespace std;
class PrintJobs { int nPages_; // # of pages in current job
static int nTrayPages_; // # of pages remaining in the tray
Partha Pratim
static int nJobs_; // # of print jobs executing
Das
public: PrintJobs(int nP) : nPages_(nP) { ++nJobs_;
cout << "Printing " << nP << " pages" << endl;
Objectives & nTrayPages_ = nTrayPages_ - nP;
Outline }
~PrintJobs() { --nJobs_; }
static data static int getJobs() { return nJobs_; }
member static int checkPages() { return nTrayPages_; }
Print Task static void loadPages(int nP) { nTrayPages_ += nP; }
};
static
int PrintJobs::nTrayPages_ = 500; // Definition and initialization -- load paper
Member
int PrintJobs::nJobs_ = 0; // Definition and initialization -- no job to start with
function
int main() { Output:
Print Task cout << "Jobs = " << PrintJobs::getJobs() << endl;
Singleton cout << "Pages= " << PrintJobs::checkPages() << endl; Jobs = 0
Class PrintJobs job1(10); Pages= 500
cout << "Jobs = " << PrintJobs::getJobs() << endl; Printing 10 pages
Summary cout << "Pages= " << PrintJobs::checkPages() << endl; Jobs = 1
{ PrintJobs job1(30), job2(20); Pages= 490
cout << "Jobs = " << PrintJobs::getJobs() << endl; Printing 30 pages
cout << "Pages= " << PrintJobs::checkPages() << endl; Printing 20 pages
PrintJobs::loadPages(100); Jobs = 3
} Pages= 440
cout << "Jobs = " << PrintJobs::getJobs() << endl; Jobs = 1
cout << "Pages= " << PrintJobs::checkPages() << endl; Pages= 540
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 8
Singleton Class

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Program 16.04: static Data & Member Function
Singleton Printer
#include <iostream>
Module 16 using namespace std;

class Printer { /* THIS IS A SINGLETON PRINTER -- ONLY ONE INSTANCE */


Partha Pratim
bool blackAndWhite_, bothSided_;
Das
Printer(bool bw = false, bool bs = false) : blackAndWhite_(bw), bothSided_(bs)
Objectives & { cout << "Printer constructed" << endl; } // Private -- Printer cannot be constructed!
Outline
static Printer *myPrinter_; // Pointer to the Instance of the Singleton Printer
static data
member public:
Print Task ~Printer() { cout << "Printer destructed" << endl; }
static
static const Printer& printer(bool bw = false, bool bs = false) { // Access the Printer
Member
if (!myPrinter_) myPrinter_ = new Printer(bw, bs); // Constructed for first call
function
return *myPrinter_; // Reused from next time
Print Task }
Singleton void print(int nP) const { cout << "Printing " << nP << " pages" << endl; }
Class };
Printer *Printer::myPrinter_ = 0;
int main() { Output:
Summary
Printer::printer().print(10);
Printer::printer().print(20); Printer constructed
Printing 10 pages
delete &Printer::printer(); Printing 20 pages
return 0; Printer destructed
}

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;

class Printer { /* THIS IS A SINGLETON PRINTER -- ONLY ONE INSTANCE */


Partha Pratim
bool blackAndWhite_, bothSided_;
Das
Printer(bool bw = false, bool bs = false) : blackAndWhite_(bw), bothSided_(bs)
Objectives & { cout << "Printer constructed" << endl; }
Outline
~Printer() { cout << "Printer destructed" << endl; }
static data public:
member
Print Task static const Printer& printer(bool bw = false, bool bs = false) {
static Printer myPrinter(bw, bs); // The Singleton -- constructed the first time
static
Member
return myPrinter;
function
}
Print Task void print(int nP) const {
Singleton cout << "Printing " << nP << " pages" << endl;
Class }
}; Output:
Summary int main() {
Printer::printer().print(10); Printer constructed
Printer::printer().print(20); Printing 10 pages
Printing 20 pages
return 0; Printer destructed
}

• Function local static object is used


• No memory management overhead – so destructor too get private
• This is called Meyer’s Singleton
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Module Summary

Module 16

Partha Pratim Introduced static data member


Das
Introduced static member function
Objectives &
Outline Exposed to use of static members
static data
member Singleton Class discussed
Print Task

static
Member
function
Print Task

Singleton
Class

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Module 17

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 17

Partha Pratim Understand friend function and class


Das

Objectives &
Outline

friend
function
Matrix-Vector
Multiplication
Linked List

friend class
Linked List
Iterator

Notes

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 17

Partha Pratim friend function


Das
Matrix-Vector Multiplication
Objectives & Linked List
Outline
friend class
friend
function Linked List
Matrix-Vector
Multiplication Iterator
Linked List

friend class friend-ly Notes


Linked List
Iterator

Notes

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Program 17.01: friend function – Basic Notion
Ordinary function friend function
Module 17
#include<iostream> #include<iostream>
Partha Pratim using namespace std; using namespace std;
Das
class MyClass { int data_; class MyClass { int data_;
public: public:
Objectives & MyClass(int i) : data_(i) {} MyClass(int i) : data_(i) {}
Outline
friend void display(const MyClass& a);
friend }; };
function void display(const MyClass& a) { void display(const MyClass& a) {
Matrix-Vector cout << "data = " << a.data_; // Error 1 cout << "data = " << a.data_; // Okay
Multiplication
} }
Linked List
int main(){ int main(){
friend class MyClass obj(10); MyClass obj(10);
Linked List
Iterator display(obj); display(obj);

Notes return 0; return 0;


} }
Summary
• display() is a non-member function • display() is a non-member function; but
friend to class MyClass
• Error 1: ’MyClass::data ’ : cannot • Able to access data even though it is private
access private member declared in class in class MyClass
’MyClass’
• Output: data = 10

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

Partha Pratim A friend function of a class


Das has access to the private and protected members of the class (breaks
the encapsulation)
Objectives &
Outline
must have its prototype included within the scope of the class
prefixed with the keyword friend
friend does not have its name qualified with the class scope
function
Matrix-Vector
is not called with an invoking object of the class
Multiplication can be declared friend in more then one classes
Linked List

friend class A friend function can be a


Linked List global function
Iterator
a member function of a class
Notes
a function template
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Program 17.02: Multiply a Matrix with a Vector
#include <iostream> class Matrix { int e_[3][3]; int m_, n_;
Module 17 using namespace std; public:
Matrix(int m, int n) : m_(m), n_(n) {
Partha Pratim class Matrix; // Forward declaration // Arbitrary initialization
Das for (int i = 0; i < m_; ++i)
class Vector { int e_[3]; int n_; for (int j = 0; j < n_; ++j)
public: e_[i][j] = i + j;
Objectives & Vector(int n) : n_(n) { }
Outline // Arbitrary initialization void Show() { //Show the matrix
for (int i = 0; i < n_; ++i) for (int i = 0; i < m_; ++i) {
friend e_[i] = i + 1; for (int j = 0; j < n_; ++j)
function } cout << e_[i][j] << " ";
Matrix-Vector void Clear() { // Set a zero vector cout << endl;
Multiplication
for (int i = 0; i < n_; ++i) }
Linked List
e_[i] = 0; cout << endl;
friend class } }
Linked List void Show() { //Show the vector friend Vector Prod(Matrix *pM,
Iterator for (int i = 0; i < n_; ++i) Vector *pV);
cout << e_[i] << " "; };
Notes cout << endl << endl; Vector Prod(Matrix *pM, Vector *pV) {
} Vector v(pM->m_); v.Clear();
Summary friend Vector Prod(Matrix *pM, for (int i = 0; i < pM->m_; i++)
Vector *pV); for (int j = 0; j < pM->n_; j++)
}; v.e_[i] += pM->e_[i][j] * pV->e_[j];
return v;
}

• Vector Prod(Matrix*, Vector*); is a global function


• Vector Prod(Matrix*, Vector*); is friend of class Vector as well as class Matrix
• This function accesses the private data members of both these classes
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Program 17.02: Multiply a Matrix with a Vector
int main() { Output:
Module 17 Matrix M(2, 3);
Vector V(3); 0 1 2
Partha Pratim 1 2 3
Das Vector PV = Prod(&M, &V);
1 2 3
M.Show();
Objectives & 8 14
V.Show();
Outline
PV.Show();
friend
function return 0;
}
Matrix-Vector
Multiplication
Linked List
• Vector Prod(Matrix*, Vector*); is a global function
friend class • Vector Prod(Matrix*, Vector*); is friend of class Vector as well as class Matrix
Linked List • This function accesses the private data members of both these classes
Iterator

Notes

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Program 17.03: Linked List
#include <iostream> void List::display() {
Module 17 using namespace std; Node *ptr = head;
while (ptr) {
Partha Pratim class Node; // Forward declaration cout << ptr->info << " ";
Das ptr = ptr->next;
class List { }
Node *head; // Head of the list }
Objectives & Node *tail; // Tail of the list
Outline public: void List::append(Node *p) {
List(Node *h = 0): if (!head) head = tail = p;
friend head(h), else {
function tail(h) {} tail->next = p;
Matrix-Vector void display(); tail = tail->next;
Multiplication
void append(Node *p); }
Linked List
}; }
friend class
Linked List class Node { int main() {
Iterator int info; // Data of the node List l; // Init null list
Node *next; // Ptr to next node Node n1(1), n2(2), n3(3); // Few nodes
Notes public: l.append(&n1); // Add nodes to list
Node(int i): info(i), next(0) { } l.append(&n2);
Summary friend void List::display(); l.append(&n3);
friend void List::append(Node *); l.display(); // Show list
}; return 0;
}

• 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

Partha Pratim A friend class of a class


Das has access to the private and protected members of the class (breaks
the encapsulation)
Objectives &
Outline
does not have its name qualified with the class scope (not a nested
class)
friend can be declared friend in more then one classes
function
Matrix-Vector
Multiplication A friend class can be a
Linked List
class
friend class class template
Linked List
Iterator

Notes

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Program 17.04: Linked List
#include <iostream> void List::display() {
Module 17 using namespace std; Node *ptr = head;
while (ptr) {
Partha Pratim class Node; // Forward declaration cout << ptr->info << " ";
Das ptr = ptr->next;
class List { }
Node *head; // Head of the list }
Objectives & Node *tail; // Tail of the list
Outline public: void List::append(Node *p) {
List(Node *h = 0): if (!head) head = tail = p;
friend head(h), else {
function tail(h) {} tail->next = p;
Matrix-Vector void display(); tail = tail->next;
Multiplication
void append(Node *p); }
Linked List
}; }
friend class
Linked List class Node { int main() {
Iterator int info; // Data of the node List l; // Init null list
Node *next; // Ptr to next node Node n1(1), n2(2), n3(3); // Few nodes
Notes public: l.append(&n1); // Add nodes to list
Node(int i): info(i), next(0) { } l.append(&n2);
Summary //friend void List::display(); l.append(&n3);
//friend void List::append(Node *);
friend class List; l.display(); // Show list
}; return 0;
}

• 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Program 17.05: Linked List with Iterator
#include <iostream> void Iterator::begin(List *l) {
Module 17 using namespace std; list = l; node = l->head; // Set list & Init
}
class Node; class List; bool Iterator::end() { return node == 0; }
Partha Pratim
class Iterator { void Iterator::next() { node = node->next; }
Das
Node *node; // Current Node int Iterator::data() { return node->info; }
List *list; // Current List
Objectives & public: void List::append(Node *p) {
Outline Iterator() : node(0), list(0) {} if (!head)
void begin(List *); // Init head = tail = p;
friend bool end(); // Check end else {
function void next(); // Go to next tail->next = p;
Matrix-Vector int data(); // Get node data tail = tail->next;
Multiplication
}; }
Linked List
class List { Node *head, *tail; }
friend class public: int main() {
Linked List List(Node *h=0): head(h), tail(h) {} List l; Node n1(1), n2(2), n3(3);
Iterator void append(Node *p); l.append(&n1); l.append(&n2); l.append(&n3);
friend class Iterator;
Notes }; Iterator i;
class Node { int info; Node *next; for (i.begin(&l); !i.end(); i.next()) {
Summary public: cout << i.data() << " ";
Node(int i) : info(i), next(0) { } }
friend class List;
friend class Iterator; return 0;
}; }

• An Iterator now traverses over the elements of the List


• void List::display() is dropped from List and can be written in main()
• List class is a friend of Node class
• Iterator class is a friend of List and Node classs
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
friend-ly Notes

Module 17 friend-ship is neither commutative nor transitive


Partha Pratim A is a friend of B does not imply that B is a friend of A
Das A is a friend of B and B is a friend of C does not imply that A is a
friend of C
Objectives &
Outline Visibility and Encapsulation
friend public: a declaration that is accessible to all
function protected: a declaration that is accessible only to the class itself and
Matrix-Vector
Multiplication its subclasses
Linked List private: a declaration that is accessible only to the class itself
friend class friend: a declaration that is accessible only to friend’s of a class.
Linked List friend’s tend to break data hiding and should be used judiciously.
Iterator
Like:
Notes
A function needs to access the internals of two (or more)
Summary
independent classes (Matrix-Vector Multiplication)
A class is built on top of another (List-Node Access, List
Iterator)
Certain situations of operator overloading (like streaming
operators)

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Module Summary

Module 17

Partha Pratim Introduced the notion of friend function


Das
Introduced the notion of friend class
Objectives &
Outline Studied the use of friend function and friend class with
friend
function
examples
Matrix-Vector
Multiplication friend introduces visibility hole by breaking encapsulation
Linked List
– should be used with care
friend class
Linked List
Iterator

Notes

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Module 18

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 18

Partha Pratim Understand how to overload operators for a user-defined


Das
type (class)
Objectives &
Outline Understand the aspects of overloading by global function
Motivation and member function
Operator
Function

Using global
function
public data
members
private data
members

Using member
function
operator+
operator=
Unary Operators

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 18

Partha Pratim Motivation


Das
Operator Function
Objectives &
Outline Using Global function
Motivation public data members
Operator private data members
Function

Using global
Using Member function
function operator+
public data
members operator=
private data
members Unary operators
Using member
function
operator+
operator=
Unary Operators

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Motivation

Module 18 We have seen how overloading operator+ a C-string wrapped in struct


allows us a compact notation for concatenation of two strings (Module 09)
Partha Pratim
Das We have see how overloading operator= can define the deep / shallow copy
for a UDT and / or help with user-defined copy semantics (Module 14)
Objectives &
Outline
In general, operator overloading helps us build complete algebra for UDT’s
much in the same line as is available for built-in types:
Motivation
Complex type: Add (+), Subtract (–), Multiply (*), Divide (/),
Operator
Function Conjugate (!), Compare (==, !=, ...), etc.
Fraction type: Add (+), Subtract (–), Multiply (*), Divide (/),
Using global
function
Normalize (unary *), Compare (==, !=, ...), etc.
public data Matrix type: Add (+), Subtract (–), Multiply (*), Divide (/), Invert
members
private data
(!), Compare (==), etc.
members Set type: Union (+), Difference (–), Intersection (*), Subset (<,
Using member <=), Superset (>, >=), Compare (==, !=), etc.
function
Direct IO: read (<<) and write (>>) for all types
operator+
operator=
Unary Operators
Advanced examples include:
Summary Smart Pointers: De-reference (unary *), Indirection (− >), Copy
(=), Compare (==, !=), etc.
Function Objects or Functors: Invocation ( () )
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Operator Functions in C++: RECAP (Module 9)
Introduces a new keyword: operator
Module 18
Every operator is associated with an operator function that defines its
Partha Pratim
Das
behavior

Operator Expression Operator Function


Objectives &
Outline a + b operator+(a, b)
Motivation a = b operator=(a, b)
c = a + b operator=(c, operator+(a, b))
Operator
Function Operator functions are implicit for predefined operators of built-in types
Using global and cannot be redefined
function
An operator function may have a signature as:
public data
members
private data MyType a, b; // An enum or struct
members

Using member // Operator function


function
operator+
MyType operator+(const MyType&, const MyType&);
operator=
Unary Operators a + b // Calls operator+(a, b)
Summary
C++ allows users to define an operator function and overload it

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Non-Member Operator Function

Module 18 A non-member operator function may be a


Partha Pratim Global Function
Das friend Function
Binary Operator:
Objectives &
Outline MyType a, b; // An enum, struct or class
Motivation MyType operator+(const MyType&, const MyType&); // Global
friend MyType operator+(const MyType&, const MyType&); // Friend
Operator
Function Unary Operator:
Using global MyType operator++(const MyType&); // Global
function friend MyType operator++(const MyType&); // Friend
public data
members Note: The parameters may not be constant and may be passed by value.
private data
members The return may also be by reference and may be constant
Using member Examples:
function
Operator Expression Operator Function
operator+
operator= a + b operator+(a, b)
Unary Operators
a = b operator=(a, b)
Summary ++a operator++(a)
a++ operator++(a, int) Special Case
c = a + b operator=(c, operator+(a, b))
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Member Operator Function

Module 18 Binary Operator:


MyType a, b; // MYType is a Class
Partha Pratim
Das MyType operator+(const MyType&); // Operator function

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

Partha Pratim Intrinsic properties of the overloaded operator cannot be change


Das
Preserves arity
Preserves precedence
Objectives &
Outline Preserves associativity
Motivation These operators can be overloaded:
Operator [] + - * / % & | ~ ! = += -= *= /= %= = &= |=
Function << >> >>= <<= == != < > <= >= && || ++ -- , ->* -> ( ) [ ]
Using global The operators :: (scope resolution), . (member access), .* (member access
function through pointer to member), sizeof, and ?: (ternary conditional) cannot
public data
members be overloaded
private data
members The overloads of operators &&, ||, and , (comma) lose their special
Using member properties: short-circuit evaluation and sequencing
function
The overload of operator-> must either return a raw pointer or return an
operator+
operator= object (by reference or by value), for which operator-> is in turn overloaded
Unary Operators
For a member operator function, invoking object is passed implicitly as the
Summary left operand but the right operand is passed explicitly
For a non-member operator function (Global/friend) operands are always
passed explicitly
NPTEL MOOCs Programming in C++ Partha Pratim Das 8
Program 18.01: Using Global Function – Unsafe
(public Data members)
Overloading + for complex addition Overloading + for string cat
Module 18
#include <iostream> #include <iostream>
Partha Pratim using namespace std; #include <cstring>
Das struct complx { // public data member using namespace std;
double re; typedef struct _String { char *str; } String;
double im; String operator+(const String& s1,
Objectives & } ; const String& s2) {
Outline complx operator+ (complx &a, complx &b) { String s;
complx r; s.str = (char *) malloc(strlen(s1.str) +
Motivation r.re = a.re + b.re; strlen(s2.str) + 1);
r.im = a.im + b.im; strcpy(s.str, s1.str);
Operator
return r; strcat(s.str, s2.str);
Function
} return s;
Using global int main(){ }
function complx d1 , d2 , d; int main() {
d1.re = 10.5; d1.im = 12.25; String fName, lName, name;
public data
members d2.re = 20.5; d2.im = 30.25; fName.str = strdup("Partha ");
private data d = d1 + d2; lName.str = strdup("Das");
members cout <<"Real:" << d.re; name = fName + lName; // Overload operator +
cout << "Imaginary:" << d.im; cout << "First Name: " << fName.str << endl;
Using member
return 0; cout << "Last Name: " << lName.str << endl;
function
} cout << "Full Name: " << name.str << endl;
operator+
return 0;
operator=
}
Unary Operators

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 • Accessing private data members inside operator functions is clumsy


• Critical data members need to be exposed (get/set) violating encapsulation
• Solution: Member operator function or friend operator function

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Program 18.03: Using Member Function

Module 18 #include <iostream>


void Complex::display(){
using namespace std;
cout << re;
Partha Pratim class Complex { // Private data members
cout << " +j " << im << endl;
Das double re, im;
}
public:
int main() {
Complex(double a=0.0, double b=0.0):
Objectives & Complex c1(4.5, 25.25), c2(8.3, 10.25), c3;
re(a), im(b) {}
Outline cout << "1st complex No:";
~Complex() {}
c1.display();
void display(); •
Motivation cout << "2nd complex No:";
Complex operator+(const Complex &c) {
c2.display();
Operator Complex r;
c3 = c1 + c2;
Function r.re = re + c.re;
cout << "Sum = ";
r.im = im + c.im;
c3.display();
Using global return r;
return 0;
function }
}
public data } ;
members
private data Output:
members

Using member 1st complex No: 4.5 +j 25.25


function 2nd complex No: 8.3 +j 10.25
operator+ Sum = 12.8 +j 35.5
operator=
Unary Operators • Performing c1 + c2 is equivalent to c1.operator+(c2)
• c1 invokes the operator+ function and c2 is passed as an argument
Summary
• Similarly we can implement all binary operators (%,-,* etc..)
• Note: No need of two arguments in overloading

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Program 14.14: Overloading operator=
RECAP (Module 14)
#include <iostream>
Module 18 #include <cstdlib>
#include <cstring>
Partha Pratim using namespace std;
Das
class String { public: char *str_; size_t len_;
String(char *s) : str_(strdup(s)), len_(strlen(str_)) { } // ctor
Objectives &
String(const String& s) : str_(strdup(s.str_)), len_(s.len_) { } // cctor
Outline
~String() { free(str_); } // dtor
Motivation String& operator=(const String& s) {
if (this != &s) {
Operator free(str_);
Function str_ = strdup(s.str_);
len_ = s.len_;
Using global }
function return *this;
public data }
members void print() { cout << "(" << str_ << ": " << len_ << ")" << endl; }
private data };
members
int main() { String s1 = "Football", s2 = "Cricket";
Using member s1.print(); s2.print();
function s1 = s1; s1.print();
operator+ return 0;
operator= }
Unary Operators ---
(Football: 8)
Summary (Cricket: 7)
(Football: 8)

• Check for self-copy (this != &s)


• In case of self-copy, do nothing
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Notes on Overloading operator=
RECAP (Module 14)
Module 18 Overloaded operator= may choose between Deep and
Partha Pratim Shallow Copy for Pointer Members
Das
Deep copy allocates new space for the contents and copies
Objectives & the pointed data
Outline
Shallow copy merely copies the pointer value – hence, the
Motivation
new copy and the original pointer continue to point to the
Operator
Function
same data
Using global If operator= is not overloaded by the user, compiler
function
public data provides a free one.
members
private data
members Free operator= can makes only a shallow copy
Using member
function If the constructor uses operator new, operator= should
operator+
operator=
be overloaded
Unary Operators

Summary
If there is a need to define a copy constructor then
operator= must be overloaded and vice-versa

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Program 18.04: Overloading Unary Operators
• Output
Module 18 #include <iostream>
Data = 8
using namespace std;
Data = 8
Partha Pratim Data = 9
Das class MyClass { int data;
Data = 10
public:
Data = 10
MyClass(int d): data(d) { }
Objectives &
Outline MyClass& operator++() { // Pre-increment:
++data; // Operate and return the operated object
Motivation return *this;
}
Operator
MyClass operator++(int) { // Post-Increment:
Function
MyClass t(data); // Return the (copy of) object; operate the object
Using global ++data;
function return t;
public data
}
members void disp() { cout << "Data = " << data << endl; }
private data };
members
• The pre-operator should first perform the op-
int main() {
eration (increment / decrement / other) and
Using member MyClass obj1(8);
then return the object. Hence its return type
function obj1.disp();
should be MyClass& and it should return *this;
operator+
MyClass obj2 = obj1++;
operator= • The post-operator should perform the oper-
obj2.disp(); obj1.disp();
Unary Operators ation (increment / decrement / other) after it
returns the original value. Hence it should copy
Summary obj2 = ++obj1;
the original object in a temporary MyClass t; and
obj2.disp(); obj1.disp();
then return t;. Its return type should be MyClass
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 14
Program 18.05: Overloading Unary Operators:
Pre-increment & Post Increment
#include <iostream>
• Output
Module 18 using namespace std;
Data = 12
Data = 12
Partha Pratim class MyClass { int data;
Data = 4
Das public:
Data = 8
MyClass(int d) : data(d) { }
Data = 8
Objectives &
MyClass& operator++() { // Pre-Operator
Outline
data *= 2;
Motivation return *this;
}
Operator MyClass operator++(int) { // Post-Operator
Function MyClass t(data);
data /= 3;
Using global return t;
function }
public data void disp() { cout << "Data = " << data << endl; }
members };
private data int main(){
members • The pre-operator and the post-operator need
MyClass obj1(12);
not merely increment / decrement
Using member obj1.disp();
function • They may be used for any other compuation
operator+ MyClass obj2 = obj1++;
as this example shows
operator= obj2.disp(); obj1.disp();
Unary Operators • However, it is a good design practice to keep
obj2 = ++obj1;
Summary close to the native semantics of the operator
obj2.disp(); obj1.disp();

return 0;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Module Summary

Module 18

Partha Pratim Introduced operator overloading for user-defined types


Das
Illustrated methods of overloading operators using global
Objectives &
Outline functions and member functions
Motivation Outlined semantics for overloading binary and unary
Operator
Function
operators
Using global
function
public data
members
private data
members

Using member
function
operator+
operator=
Unary Operators

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 16


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Module 19

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+

Overloading Department of Computer Science and Engineering


IO Operators Indian Institute of Technology, Kharagpur
Guidelines [email protected]
Summary

Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 19

Partha Pratim Understand how to overload operators for a user-defined


Das
type (class)
Objectives &
Outline Understand the aspects of overloading by friend function
Issues in and its advantages
Operator
Overloading

Extending
operator+

Overloading
IO Operators

Guidelines

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 19

Partha Pratim Issues in Operator Overloading


Das
Extending operator+
Objectives &
Outline Overloading IO Operators
Issues in
Operator Guidelines for Operator Overloading
Overloading

Extending
operator+

Overloading
IO Operators

Guidelines

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Operator Function for UDT
RECAP (Module 18)
Module 19 Operator Function options:
Partha Pratim Global Function
Das Member Function
friend Function
Objectives &
Outline Binary Operator:
Issues in MyType a, b; // An enum, struct or class
Operator MyType operator+(const MyType&, const MyType&); // Global
Overloading MyType operator+(const MyType&); // Member
Extending friend MyType operator+(const MyType&, const MyType&); // Friend
operator+
Unary Operator:
Overloading
IO Operators MyType operator++(const MyType&); // Global
MyType operator++(); // Member
Guidelines
friend MyType operator++(const MyType&); // Friend
Summary
Examples:
Expression Function Remarks
a + b operator+(a, b) global / friend
++a operator++(a) global / friend
a + b a.operator+(b) member
++a a.operator++() member

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Issue 1: Extending operator+

Module 19 Consider a Complex class. We have learnt how to overload operator+ to


Partha Pratim
add two Complex numbers:
Das
Complex d1(2.5, 3.2), d2(1.6, 3.3), d3;
Objectives &
Outline
d3 = d1 + d2; // d3 = 4.1 +j 6.5
Issues in
Operator
Overloading Now we want to extend the operator so that a Complex number and a real
Extending number (no imaginary part) can be added together:
operator+

Overloading
IO Operators
Complex d1(2.5, 3.2), d2(1.6, 3.3), d3;

Guidelines d3 = d1 + 6.2; // d3 = 8.7 +j 3.2


Summary
d3 = 4.2 + d2; // d3 = 5.8 +j 3.3

We show why global operator function is not good for this


We show why member operator function cannot do this
We show how friend function achieves this
NPTEL MOOCs Programming in C++ Partha Pratim Das 5
Issue 2: Overloading IO Operators:
operator<<, operator>>
Module 19 Consider a Complex class. Suppose we want to overload the streaming
Partha Pratim
operators for this class so that we can write the following code:
Das
Complex d;
Objectives &
Outline
cin >> d;
Issues in
Operator
Overloading cout << d;
Extending
operator+ Let us note that these operators deal with stream types defined in
Overloading iostream, ostream, and istream:
IO Operators
cout is an ostream object
Guidelines cin is an istream object
Summary
We show why global operator function is not good for this
We show why member operator function cannot do this
We show how friend function achieves this

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Program 19.01: Extending operator+
with Global Function
#include <iostream>
Module 19 using namespace std;
class Complex { public: double re, im;
explicit Complex(double r = 0, double i = 0): re(r), im(i) { }
Partha Pratim
void disp() { cout << re << " +j " << im << endl; }
Das
};
Complex operator+ (const Complex &a, const Complex &b) { // Overload 1
Objectives & return Complex(a.re + b.re, a.im + b.im);
Outline }
Complex operator+ (const Complex &a, double d) { // Overload 2
Issues in Complex b(d); return a + b; // Create temporary object and use Overload 1
Operator }
Overloading Complex operator+ (double d, const Complex &b) { // Overload 3
Complex a(d); return a + b; // Create temporary object and use Overload 1
Extending }
operator+ int main(){
Overloading Complex d1(2.5, 3.2), d2(1.6, 3.3), d3;
IO Operators
d3 = d1 + d2; d3.disp(); // d3 = 4.1 +j 6.5
Guidelines d3 = d1 + 6.2; d3.disp(); // d3 = 8.7 +j 3.2
d3 = 4.2 + d2; d3.disp(); // d3 = 5.8 +j 3.3
Summary return 0;
}

• Works fine with global functions - 3 separate overloading are provided


• A bad solution as it breaks the encapsulation – as discussed in Module 18
• Let us try to use member function

• 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Program 19.02: Extending operator+
with Member Function
#include <iostream>
Module 19 using namespace std;
class Complex { double re, im;
public:
Partha Pratim
explicit Complex(double r = 0, double i = 0) : re(r), im(i) { }
Das
void disp() { cout << re << " +j " << im << endl; }
Complex operator+ (const Complex &a) { // Overload 1
Objectives & return Complex(re + a.re, im + a.im);
Outline }
Complex operator+ (double d) { // Overload 2
Issues in Complex b(d); return *this + b; // Create temporary object and use Overload 1
Operator }
Overloading };
int main(){
Extending Complex d1(2.5, 3.2), d2(1.6, 3.3), d3;
operator+

Overloading d3 = d1 + d2; d3.disp(); // d3 = 4.1 +j 6.5


IO Operators d3 = d1 + 6.2; d3.disp(); // d3 = 8.7 +j 3.2

Guidelines //d3 = 4.2 + d2; // Overload 3 is not possible - needs an object of left
//d3.disp();
Summary return 0;
}

• Overload 1 and 2 works


• Overload 3 cannot be done because the left operand is double – not an object
• Let us try to use friend function

• Note: This solution too avoids the feature of cast operators

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Program 19.03: Extending operator+
with friend Function
#include <iostream>
Module 19 using namespace std;
class Complex { double re, im; public:
explicit Complex(double r = 0, double i = 0) : re(r), im(i) { }
Partha Pratim
void disp() { cout << re << " +j " << im << endl; }
Das
friend Complex operator+ (const Complex &a, const Complex &b) { // Overload 1
return Complex(a.re + b.re, a.im + b.im);
Objectives & }
Outline friend Complex operator+ (const Complex &a, double d) { // Overload 2
Complex b(d); return a + b; // Create temporary object and use Overload 1
Issues in }
Operator friend Complex operator+ (double d, const Complex &b) { // Overload 3
Overloading Complex a(d); return a + b; // Create temporary object and use Overload 1
}
Extending };
operator+

Overloading int main(){


IO Operators Complex d1(2.5, 3.2), d2(1.6, 3.3), d3;

Guidelines d3 = d1 + d2; d3.disp(); // d3 = 4.1 +j 6.5


d3 = d1 + 6.2; d3.disp(); // d3 = 8.7 +j 3.2
Summary d3 = 4.2 + d2; d3.disp(); // d3 = 5.8 +j 3.3
return 0;
}

• Works fine with friend functions - 3 separate overloading are provided


• Preserves the encapsulation too

• 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Overloading IO Operators:
operator<<, operator>>
Module 19 Consider operator<< for Complex class. This operator should take an
Partha Pratim
ostream object (stream to write to) and a Complex (object to write).
Das Further it allows to chain the output. So for the following code

Objectives &
Outline
Complex d1, d2;

Issues in cout << d1 << d2; // (cout << d1) << d2;
Operator
Overloading

Extending the signature of operator<< may be one of:


operator+
// Global function
Overloading
IO Operators
ostream& operator<< (ostream& os, const Complex &a);

Guidelines // Member function in ostream


Summary ostream& ostream::operator<< (const Complex &a);

// Member function in Complex


ostream& Complex::operator<< (ostream& os);
Object to write is passed by constant reference
Return by reference for ostream object is used so that chaining would work

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Program 19.04: Overloading IO Operators
with Global Function
#include <iostream>
Module 19
using namespace std;
class Complex {
Partha Pratim public: double re, im;
Das Complex(double r = 0, double i = 0): re(r), im(i) { }
};
Objectives & ostream& operator<< (ostream& os, const Complex &a) {
Outline os << a.re << " +j " << a.im << endl;
return os;
Issues in }
Operator istream& operator>> (istream& is, Complex &a) {
Overloading is >> a.re >> a.im;
return is;
Extending }
operator+
int main(){
Overloading Complex d;
IO Operators

Guidelines cin >> d;

Summary cout << d;

return 0;
}

• Works fine with global functions


• A bad solution as it breaks the encapsulation – as discussed in Module 18
• Let us try to use member function

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Overloading IO Operators with Member Function

Module 19 Case 1: operator<< is a member in ostream class:


Partha Pratim
Das ostream& ostream::operator<< (const Complex &a);
Objectives &
Outline This is not possible as ostream is a class in C++ standard library and we
are not allowed to edit it to include the above signature
Issues in
Operator Case 2: operator<< is a member in Complex class:
Overloading

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

This certainly spoils the natural syntax


IO operators cannot be overloaded by member functions
Let us try to use friend function

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Guidelines for Operator Overloading

Use global function when encapsulation is not a concern. For example,


Module 19
using struct String { char* str; } to wrap a C-string and overload
Partha Pratim operator+ to concatenate strings and build a String algebra
Das
Use member function when the left operand is necessarily a class where the
Objectives & operator function is a member and multiple types of operands are not
Outline involved
Issues in Use friend function, otherwise
Operator
Overloading While overloading an operator, try to preserve its natural semantics for
built-in types as much as possible. For example, operator+ in a Set class
Extending
operator+ should compute union and NOT intersection
Overloading Usually stick to the parameter passing conventions (built-in types by value
IO Operators and UDT’s by constant reference)
Guidelines Decide on the return type based on the natural semantics for built-in types.
Summary
For example, as in pre-increment and post-increment operators
Consider the effect of casting on operands
Only overload the operators that you may need (minimal design)

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Module Summary

Module 19

Partha Pratim Several issues operator overloading has been discussed


Das
Use of friend is illustrated in versatile forms of
Objectives &
Outline overloading with examples
Issues in
Operator
Discussed the overloading IO (streaming) operators
Overloading
Guidelines for operator overloading is summarized
Extending
operator+ Use operator overloading to build algebra for:
Overloading Complex numbers
IO Operators
Fractions
Guidelines
Strings
Summary
Vector and Matrices
Sets
and so on ...

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Module 20

Partha Pratim
Das Module 20: Programming in C++
Objectives & Namespace
Outline

namespace
Fundamental

namespace Partha Pratim Das


Scenarios

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

Partha Pratim Understand namespace as a free scoping mechanism to


Das
organize code better
Objectives &
Outline

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

Partha Pratim namespace Fundamental


Das
namespace Scenarios
Objectives &
Outline namespace Features
namespace Nested namespace
Fundamental
using namespace
namespace
Scenarios Global namespace
namespace Standard Library std namespace
Features namespaces are open
Nested
namespace
using namespace namespace vis-a-vis class
Global
namespace
std namespace
Lexical Scope
namespaces are
Open

namespace
vis-a-vis class

Lexical Scope

Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 3
namespace Fundamental

Module 20 A namespace is a declarative region that provides a scope


Partha Pratim to the identifiers (the names of types, functions, variables,
Das
etc) inside it
Objectives &
Outline It is used to organize code into logical groups and to
namespace prevent name collisions that can occur especially when
Fundamental
your code base includes multiple libraries
namespace
Scenarios namespace provides a class-like modularization without
namespace
Features
class-like semantics
Nested
namespace Obliviates the use of File Level Scoping of C (file )static
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 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);

namespace int main() {


Scenarios St s1("Ramala", St::female); reg->add(&s1);
St s2("Partha", St::male); reg->add(&s2);
namespace
Features ProcessStduents(); // Function from App1.cpp by Sabita
Nested ProcessStduents(); // Function from App2.cpp by Niloy
namespace
using namespace
Global return 0;
namespace }
std namespace
But the integration failed due to name clashes
namespaces are
Open Both use the same signature void ProcessStduents(); for their respective processing function.
Actually, they have several functions, classes, and variables in their respective development with
namespace
the same name and with same / different purposes
vis-a-vis class
How does Purnima perform the integration without major changes in the codes? –
Lexical Scope namespace
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Scenario 2: Students’ Record Application:
Wrap in Namespace (Program 20.03)
Introduce two namespaces – App1 for Sabita and App2 for Niloy
Module 20
Wrap the respective codes:
Partha Pratim
Das Processing for males by Sabita Processing for females by Niloy
////////////// App1.cpp ////////////// ////////////// App2.cpp //////////////
#include <iostream> #include <iostream>
Objectives & using namespace std; using namespace std;
Outline
#include "Students.h" #include "Students.h"
namespace
Fundamental extern StReg *reg; extern StReg *reg;
namespace
namespace App1 { namespace App2 {
Scenarios
void ProcessStduents() { void ProcessStduents() {
namespace cout << "MALE STUDENTS: " << endl; cout << "FEMALE STUDENTS: " << endl;
Features int r = 1; int r = 1;
St *s; St *s;
Nested
namespace
using namespace while (s = reg->getStudent(r++)) while (s = reg->getStudent(r++))
Global if (s->getGender() == St::male) if (s->getGender() == St::female)
namespace cout << *s; cout << *s;
std namespace
namespaces are cout << endl << endl; cout << endl << endl;
Open
return; return;
namespace } }
vis-a-vis class }; };

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"

Objectives & namespace App1 { void ProcessStduents(); } // App1.cpp by Sabita


Outline
namespace App2 { void ProcessStduents(); } // App2.cpp by Niloy
namespace
Fundamental StReg *reg = new StReg(1000);

namespace int main() {


Scenarios St s1("Ramala", St::female); reg->add(&s1);
St s2("Partha", St::male); reg->add(&s2);
namespace
Features App1::ProcessStduents(); // App1.cpp by Sabita
Nested App2::ProcessStduents(); // App2.cpp by Niloy
namespace
using namespace
Global return 0;
namespace }
std namespace
Clashing names are made distinguishable by distinct namespace names
namespaces are
Open

namespace
vis-a-vis class

Lexical Scope

Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Program 20.04: Nested namespace

A namespace may be nested in another namespace


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

Objectives & int data = 0; // Global name ::


Outline

namespace namespace name1 {


Fundamental int data = 1; // In namespace name1
namespace namespace name2 {
Scenarios int data = 2; // In nested namespace name1::name2
namespace
}
Features }
Nested
namespace
using namespace int main() {
Global
namespace
cout << data << endl; // 0
std namespace cout << name1::data << endl; // 1
namespaces are cout << name1::name2::data << endl; // 2
Open

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

Partha Pratim #include <iostream>


Das using namespace std;

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

using or using namespace hides some of the names


Module 20

Partha Pratim #include <iostream>


Das using namespace std;

int data = 0; // Global Data


Objectives &
Outline
namespace name1 {
namespace int data = 1; // namespace Data
Fundamental }

namespace int main() {


Scenarios using name1::data;

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

#include <iostream> #include <iostream>


Objectives & using namespace std;
Outline
int main(){ int main(){
namespace int num; int num;
Fundamental std::cout << "Enter a value: " ; cout << "Enter a value: " ;
std::cin >> num; cin >> num;
namespace std::cout << "value is: " ; cout << "value is: " ;
Scenarios std::cout << num ; cout << num ;
namespace return 0; return 0;
Features } }
Nested • Here, cout, cin are explicitly qualified by their • By the statement using namespace std;
namespace
namespace. So, to write to standard output, we std namespace is brought into the current
using namespace
Global
specify std::cout; to read from standard input, namespace, which gives us direct access to the
namespace we use std::cin names of the functions and classes defined within
std namespace the library without having to qualify each one
namespaces are with std::
Open

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

namespace namespace open


Scenarios
{ int y = 40; }
namespace
Features int main() {
Nested
namespace using namespace open;
using namespace x = y = 20;
Global
namespace cout << x << " " << y ;
std namespace
return 0 ;
namespaces are
Open }
namespace
vis-a-vis class Output: 20 20
Lexical Scope

Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 16
namespace vis-a-vis class

Module 20 namespace class


Partha Pratim
Das • Every namespace is not a class • Every class defines a namespace
• A namespace can be reopened and • A class cannot be reopened
Objectives & more declaration added to it
Outline
• No instance of a namespace can be • A class has multiple instances
namespace created
Fundamental • using-declarations can be used to • No using-like declaration for a
namespace short-cut namespace qualification class
Scenarios • A namespace may be unnamed • An unnamed class is not allowed
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 17
Lexical Scope

The scope of a name binding an association of a name to an entity, such


Module 20
as a variable is the part of a computer program where the binding is valid:
Partha Pratim where the name can be used to refer to the entity
Das
C++ supports a variety of scopes:
Objectives & Expression Scope – restricted to one expression, mostly used by
Outline
compiler
namespace Block Scope – create local context
Fundamental
Function Scope – create local context associated with a function
namespace Class Scope – context for data members and member functions
Scenarios
Namespace Scope – grouping of symbols for code organization
namespace File Scope – limit symbols to a single file
Features Global Scope – outer-most, singleton scope containing the whole
Nested
namespace program
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 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

Partha Pratim Understood namespace as a scoping tool in c++


Das
Analyzed typical scenarios that namespace helps address
Objectives &
Outline Studied several features of namespace
namespace
Fundamental Understood how namespace is placed in respect of
namespace different lexical scopes of C++
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 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

Summary Department of Computer Science and Engineering


Indian Institute of Technology, Kharagpur
[email protected]

Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 21

Partha Pratim Revisit ISA Relationship in OOAD and understand how


Das
hierarchy can be created in C++ with Inheritance
Objectives &
Outline

ISA
Relationship

Inheritance in
C++
Semantics

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 21

Partha Pratim ISA Relationship


Das
Inheritance in C++
Objectives &
Outline
Semantics
ISA
Data Members and Object Layout
Relationship Member Functions
Inheritance in Overriding
C++
Semantics
Overloading
Summary protected Access
Constructor & Destructor
Object Lifetime
Example – Phone Hierarchy
Inheritance in C++ (private)
Implemented-As Semantics

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


ISA Relationship

Module 21

Partha Pratim We often find one object is a specialization /


Das
generalization of another
Objectives &
Outline OOAD models this using ISA relationship
ISA
Relationship
C++ models ISA relationship by Inheritance of classes
Inheritance in
C++
Semantics

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


ISA Relationship

Rose ISA Flower


Module 21
Rose has the properties of Flower – like fragrance, having petals etc.
Partha Pratim
Das Rose has some additional properties – like rosy fragrance
Rose is a specialization of Flower
Objectives & Flower is a generalization of Rose
Outline
Red Rose ISA Rose
ISA
Relationship Red Rose has the properties of Rose – like rosy fragrance etc.
Inheritance in Red Rose has some additional properties – like it is red
C++ Red Rose is a specialization of Rose
Semantics
Rose is a generalization of Red Rose
Summary

TwoWheeler ISA Vehicle; ThreeWheeler ISA Vehicle

Manager ISA Employee


NPTEL MOOCs Programming in C++ Partha Pratim Das 5
Inheritance in C++: Hierarchy

Manager ISA Employee [Single Inheritance]


Module 21

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

class Vehicle; // Base Class = Employee -- Root


class TwoWheeler: public Vehicle; // Derived Class = TwoWheeler
class ThreeWheeler: public Vehicle; // Derived Class = ThreeWheeler

Red Rose ISA Rose ISA Flower [Multi-Level Inheritance]

class Flower; // Base Class = Flower -- Root


class Rose: public Flower; // Derived Class = Rose; Base Class = Rose
class RedRose: public Rose; // Derived Class = RedRose;

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Inheritance in C++: Phones
Landline Phone Smart Phone
Module 21
Call: By dial / keyboard Call: By touchscreen –
Partha Pratim Answer
Das shows number & photo
Mobile Phone By Number
Objectives &
Outline Call: By keyboard – By Name
shows number Answer
ISA
Relationship By Number Redial
By Name Set Ring Tone
Inheritance in
C++ Answer Add Contact
Semantics
Redial Number
Summary Set Ring Tone Name
Add Contact Photo
Number
Name
• There exists a substantial overlap between the functionality of the phones
• A mobile phone is more capable than a land line phone and can perform (almost)
all its functions
• A smart phone is more capable than a mobile phone and can perform (almost)
all its functions
• These phones belong to a Specialization / Generalization hierarchy
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Inheritance in C++: Semantics

Module 21 Derived ISA Base


Partha Pratim
Das

Objectives & class Base; // Base Class = Base


Outline class Derived: public Base; // Derived Class = Derived
ISA
Relationship Use keyword public after class name to denote
Inheritance in inheritance
C++
Semantics Name of the Base class follow the keyword
Summary

”Public inheritance means ”is-a.” Everything that applies


to base classes must also apply to derived classes, because
every derived class object is a base class object”
– Scott Meyers in Item 32, Effective C++ (3rd. Edition)

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Inheritance in C++: Semantics

Derived ISA Base


Module 21
Data Members
Partha Pratim
Das Derived class inherits all data members of Base class
Derived class may add data members of its own
Objectives &
Outline Member Functions
ISA Derived class inherits all member functions of Base class
Relationship
Derived class may override a member function of Base class by
Inheritance in redefining it with the same signature
C++
Semantics
Derived class may overload a member function of Base class by
redefining it with the same name; but different signature
Summary
Access Specification
Derived class cannot access private members of Base class
Derived class can access protected members of Base class
Construction-Destruction
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
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Module Summary

Module 21

Partha Pratim Revisited Hierarchy or ISA Relationship in OOAD


Das
Introduced the Semantics of Inheritance in C++
Objectives &
Outline

ISA
Relationship

Inheritance in
C++
Semantics

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Module 22

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 22

Partha Pratim Understand how inheritance impacts data members and


Das
member functions
Objectives &
Outline Introduce overriding of member function and its
Inheritance in interactions with overloading
C++
Data Members
Overrides and
Overloads

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 22

Partha Pratim ISA Relationship


Das
Inheritance in C++
Objectives &
Outline
Semantics
Inheritance in
Data Members and Object Layout
C++ Member Functions
Data Members
Overrides and Overriding
Overloads
Overloading
Summary
protected Access
Constructor & Destructor
Object Lifetime
Example – Phone Hierarchy
Inheritance in C++ (private)
Implemented-As Semantics

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Inheritance in C++: Semantics

Derived ISA Base


Module 22
Data Members
Partha Pratim
Das Derived class inherits all data members of Base class
Derived class may add data members of its own
Objectives &
Outline Member Functions
Inheritance in Derived class inherits all member functions of Base class
C++
Data Members
Derived class may override a member function of Base class by
Overrides and redefining it with the same signature
Overloads
Derived class may overload a member function of Base class by
Summary redefining it with the same name; but different signature
Access Specification
Derived class cannot access private members of Base class
Derived class can access protected members of Base class
Construction-Destruction
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
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Inheritance in C++:
Data Members and Object Layout
Module 22 Derived ISA Base
Partha Pratim
Das
Data Members
Derived class inherits all data members of Base class
Objectives &
Outline Derived class may add data members of its own
Inheritance in
C++ Object Layout
Data Members
Overrides and
Overloads
Derived class layout contains an instance of the Base class
Summary
Further, Derived class layout will have data members of its
own
C++ does not guarantee the relative position of the Base
class instance and Derived class members

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Inheritance in C++:
Data Members and Object Layout
class B { // Base Class
Module 22 int data1B_;
public:
Partha Pratim int data2B_;
Das // ...
};
Objectives &
Outline class D: public B { // Derived Class
// Inherits B::data1B_
Inheritance in // Inherits B::data2B_
C++ int infoD_; // Adds D::infoD_
Data Members public:
Overrides and / ...
Overloads };
Summary B b;

D d;

Object Layout

Object b Object d

data1B
data1B
data2B
data2B
infoD

d cannot access data1B even though data is a part of it!


d can access data2B
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Inheritance in C++:
Member Functions – Overrides and Overloads
Module 22 Derived ISA Base
Partha Pratim
Das
Member Functions
Derived class inherits all member functions of Base class
Objectives &
Outline Derived class may override a member function of Base
Inheritance in class by redefining it with the same signature
C++
Data Members
Derived class may overload a member function of Base
Overrides and
Overloads
class by redefining it with the same name; but different
Summary
signature
Derived class may add new member functions
Static Member Functions
Derived class does not inherit the static member functions
of Base class
Friend Functions
Derived class does not inherit the friend functions of Base
class
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Inheritance in C++:
Member Functions – Overrides and Overloads
Module 22 Inheritance Override & Overload

Partha Pratim class B { // Base Class class B { // Base Class


Das public: public:
void f(int i); void f(int);
void g(int i); void g(int i);
Objectives & };
};
Outline class D: public B { // Derived Class
class D: public B { // Derived Class
public: public:
Inheritance in
// Inherits B::f(int) // Inherits B::f(int)
C++
// Inherits B::g(int) void f(int); // Overrides B::f(int)
Data Members
void f(string&); // Overloads B::f(int)
Overrides and
Overloads // Inherits B::g(int)
void h(int i); // Adds D::h(int)
Summary }; };

B b; B b;
D d; D d;

b.f(1); // Calls B::f(int) b.f(1); // Calls B::f(int)


b.g(2); // Calls B::g(int) b.g(2); // Calls B::g(int)

d.f(3); // Calls B::f(int) d.f(3); // Calls D::f(int)


d.g(4); // Calls B::g(int) d.g(4); // Calls B::g(int)

d.f("red"); // Calls D::f(string&)


d.h(5); // Calls D::h(int)
• D::f(int) overrides B::f(int)
• D::f(string) overloads B::f(int)

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Module Summary

Module 22

Partha Pratim Discussed the effect of inheritance on Data Members and


Das
Object Layout
Objectives &
Outline Discussed the effect of inheritance on Member Functions
Inheritance in with special reference to Overriding and Overloading
C++
Data Members
Overrides and
Overloads

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Module 23

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 23

Partha Pratim Understand protected access specifier


Das
Understand the construction and destruction process on
Objectives &
Outline an object hierarchy
Inheritance in
C++
Revisit Object Lifetime for a hierarchy
protected
Access
Constructor &
Destructor
Object Lifetime

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 23

Partha Pratim ISA Relationship


Das
Inheritance in C++
Objectives &
Outline
Semantics
Inheritance in
Data Members and Object Layout
C++ Member Functions
protected
Access Overriding
Constructor &
Destructor Overloading
Object Lifetime

Summary
protected Access
Constructor & Destructor
Object Lifetime
Example – Phone Hierarchy
Inheritance in C++ (private)
Implemented-As Semantics

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Inheritance in C++: Semantics

Derived ISA Base


Module 23
Data Members
Partha Pratim
Das Derived class inherits all data members of Base class
Derived class may add data members of its own
Objectives &
Outline Member Functions
Inheritance in Derived class inherits all member functions of Base class
C++
protected
Derived class may override a member function of Base class by
Access redefining it with the same signature
Constructor &
Destructor Derived class may overload a member function of Base class by
Object Lifetime redefining it with the same name; but different signature
Summary
Access Specification
Derived class cannot access private members of Base class
Derived class can access protected members of Base class
Construction-Destruction
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
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Inheritance in C++:
Access Members of Base: protected Access
Module 23 Derived ISA Base
Partha Pratim
Das
Access Specification
Derived class cannot access private members of Base class
Objectives &
Outline Derived class can access public members of Base class
Inheritance in
C++ protected Access Specification
protected
Access
Constructor &
A new protected access specification is introduced for Base
Destructor
Object Lifetime
class
Summary
Derived class can access protected members of Base class
No other class or global function can access protected
members of Base class
A protected member in Base class is like public in Derived
class
A protected member in Base class is like private in other
classes or global functions

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Inheritance in C++:
protected Access
private Access protected Access
Module 23
class B { class B {
Partha Pratim private: // Inaccessible to child protected: // Accessible to child
Das // Inaccessible to others // Inaccessible to others
int data_; int data_;
public: public:
Objectives & // ... // ...
Outline void Print() { cout << "B Object: "; void Print() { cout << "B Object: ";
cout<<data_<<endl; cout<<data_<<endl;
Inheritance in } }
C++ }; };
protected class D: public B { int info_; class D: public B { int info_;
Access
public: public:
Constructor &
Destructor // ... // ...
Object Lifetime void Print() { cout << "D Object: "; void Print() { cout << "D Object: ";
cout<<data_<<", "; // Inaccessible cout<<data_<<", "; // Accessible
Summary cout<<info_<<endl; cout<<info_<<endl;
} }
}; };

B b(0); B b(0);
D d(1, 2); D d(1, 2);

b.data_ = 5; // Inaccessible to all b.data_ = 5; // Inaccessible to others

b.Print(); b.Print();
d.Print(); d.Print();

• D::Print() cannot access B::data as it is • D::Print() can access B::data as it is


private protected
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Inheritance in C++:
Streaming
Streaming in B Streaming in B & D
Module 23
class B { class B {
Partha Pratim protected: int data_; protected: int data_;
Das public: public:
friend ostream& operator<<(ostream& os, friend ostream& operator<<(ostream& os,
const B& b) { const B& b) {
Objectives & os << b.data_ << endl; os << b.data_ << endl;
Outline return os; return os;
} }
Inheritance in }; };
C++ class D: public B { int info_; class D: public B { int info_;
protected public: public:
Access
//friend ostream& operator<<(ostream& os, friend ostream& operator<<(ostream& os,
Constructor &
Destructor // const D& d) { const D& d) {
Object Lifetime // os << d.data_ << endl; os << d.data_ << endl;
// os << d.info_ << endl; os << d.info_ << endl;
Summary // return os; return os;
//} }
}; };

B b(0); B b(0);
D d(1, 2); D d(1, 2);

cout << b; cout << d; cout << b; cout << d;

B Object: 0 B Object: 0
B Object: 1 D Object: 1 2

• d printed as a B object; info missing • d printed as a D object as expected

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Inheritance in C++:
Constructor & Destructor
Module 23 Derived ISA Base
Partha Pratim
Das
Constructor-Destructor
Derived class inherits the Constructors and Destructor of
Objectives &
Outline Base class (but in a different semantics)
Inheritance in Derived class cannot override or overload a Constructor or
C++
protected
the Destructor of Base class
Access
Constructor &
Destructor
Construction-Destruction
Object Lifetime

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Inheritance in C++:
Constructor & Destructor
class B { protected: int data_;
Module 23 public:
B(int d = 0) : data_(d) { cout << "B::B(int): " << data_ << endl; }
Partha Pratim
Das ~B() { cout << "B::~B(): " << data_ << endl; }
// ...
};
Objectives & class D: public B { int info_;
Outline public:
Inheritance in D(int d, int i) : B(d), info_(i) // ctor-1: Explicit construction of Base
C++ { cout << "D::D(int, int): " << data_ << ", " << info_ << endl; }
protected
Access D(int i) : info_(i) // ctor-2: Default construction of Base
Constructor & { cout << "D::D(int): " << data_ << ", " << info_ << endl; }
Destructor
Object Lifetime ~D() { cout << "D::~D(): " << data_ << ", " << info_ << endl; }
// ...
Summary
};

B b(5);
D d1(1, 2); // ctor-1: Explicit construction of Base
D d2(3); // ctor-2: Default construction of Base

Object Layout

Object b Object d1 Object d2

1 0
5
2 3

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Inheritance in C++:
Object Lifetime
Module 23 class B { protected: int data_;
public:
Partha Pratim B(int d = 0) : data_(d) { cout << "B::B(int): " << data_ << endl; }
Das ~B() { cout << "B::~B(): " << data_ << endl; }
// ...
};
Objectives & class D: public B { int info_;
Outline public:
D(int d, int i) : B(d), info_(i) // Explicit construction of Base
Inheritance in
{ cout << "D::D(int, int): " << data_ << ", " << info_ << endl; }
C++
D(int i) : info_(i) // Default construction of Base
protected { cout << "D::D(int): " << data_ << ", " << info_ << endl; }
Access
Constructor & ~D() { cout << "D::~D(): " << data_ << ", " << info_ << endl; }
Destructor // ...
Object Lifetime };
Summary B b(0);
D d1(1, 2);
D d2(3);

Construction O/P Destruction O/P


B::B(int): 0 // Obj. b D::~D(): 0, 3 // Obj. d2
B::B(int): 1 // Obj. d1 B::~B(): 0 // Obj. d2
D::D(int, int): 1, 2 // Obj. d1 D::~D(): 1, 2 // Obj. d1
B::B(int): 0 // Obj. d2 B::~B(): 1 // Obj. d1
D::D(int): 0, 3 // Obj. d2 B::~B(): 0 // Obj. b

• First construct base class object, then derived class object


• First destruct derived class object, then base class object
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Module Summary

Module 23

Partha Pratim Understood the need and use of protected Access


Das
specifier
Objectives &
Outline Discussed the Construction and Destruction process of
Inheritance in class hierarchy and related Object Lifetime
C++
protected
Access
Constructor &
Destructor
Object Lifetime

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Module 24

Partha Pratim
Das Module 24: Programming in C++
Objectives &
Outline
Inheritance: Part 4 (Example – Phone Hierarchy)
Example –
Phone
Hierarchy

Summary
Partha Pratim Das

Department of Computer Science and Engineering


Indian Institute of Technology, Kharagpur
[email protected]

Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 24

Partha Pratim Model a hierarchy of phones using inheritance


Das

Objectives &
Outline

Example –
Phone
Hierarchy

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 24

Partha Pratim ISA Relationship


Das
Inheritance in C++
Objectives &
Outline
Semantics
Example –
Data Members and Object Layout
Phone Member Functions
Hierarchy
Overriding
Summary
Overloading
protected Access
Constructor & Destructor
Object Lifetime
Example – Phone Hierarchy
Inheritance in C++ (private)
Implemented-As Semantics

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Phone Hierarchy

Module 24 Let us model a hierarchy of phones comprising:


Partha Pratim Land line Phone
Das Mobile Phone
Objectives &
Smart Phone
Outline
We model Helper classes
Example –
Phone
Hierarchy
We model each phone separately
Summary We model the phone hierarchy

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Helper Classes

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Land line Phone Model
Landline Phone class LandlinePhone {
Module 24 PhoneNumber number_;
Call: By dial / keyboard Name subscriber_;
Partha Pratim Answer RingTone rTone_;
Das
public:
Objectives & LandlinePhone(const char *num,
Outline const char *subs);

Example – void Call(const PhoneNumber *p);


Phone
Hierarchy void Answer();

Summary friend ostream& operator<<(ostream& os,


const LandlinePhone& p);
};

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Mobile Phone Model
Mobile Phone class MobilePhone {
Module 24 PhoneNumber number_;
Call: By keyboard – Name subscriber_;
Partha Pratim RingTone rTone_;
Das shows number AddressBook aBook_;
By Number PhoneNumber *lastDial_;
void SetLastDialed(const PhoneNumber& p);
Objectives & By Name void ShowNumber();
Outline
Answer
Example – public:
Redial MobilePhone(const char *num,
Phone
Hierarchy Set Ring Tone const char *subs);

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);

friend ostream& operator<<(ostream& os,


const MobilePhone& p);
};

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Smart Phone Model

Smart Phone class SmartPhone {


Module 24 PhoneNumber number_;
Call: By touchscreen – Name subscriber_;
Partha Pratim RingTone rTone_;
Das shows number & photo AddressBook aBook_;
PhoneNumber *lastDial_;
By Number void SetLastDialed(const PhoneNumber& p);
Objectives & By Name void ShowNumber();
Outline
unsigned int size_;
Answer void DisplayPhoto();
Example –
Phone
Redial
Hierarchy Set Ring Tone public:
SmartPhone(const char *num,
Summary Add Contact const char *subs);
Number
void Call(PhoneNumber *p);
Name void Call(const Name& n);
Photo
void Answer();

void ReDial();
void SetRingTone(RingTone::RINGTONE r);
void AddContact(const char *num = 0,
const char *subs = 0);

friend ostream& operator<<(ostream& os,


const MobilePhone& p);
};

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Comparison of Phones
Landline Phone Smart Phone
Module 24
Call: By dial / keyboard Call: By touchscreen –
Partha Pratim Answer
Das shows number & photo
Mobile Phone By Number
Objectives &
Outline Call: By keyboard – By Name
shows number Answer
Example –
Phone By Number Redial
Hierarchy
By Name Set Ring Tone
Summary Answer Add Contact
Redial Number
Set Ring Tone Name
Add Contact Photo
Number
Name
• There exists a substantial overlap between the functionality of the phones
• A mobile phone is more capable than a land line phone and can perform (almost)
all its functions
• A smart phone is more capable than a mobile phone and can perform (almost)
all its functions
• These phones belong to a Specialization / Generalization hierarchy
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Hierarchy of Phones

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Compare LandlinePhone and MobilePhone

Module 24 class LandlinePhone { class MobilePhone {


PhoneNumber number_; PhoneNumber number_;
Partha Pratim Name subscriber_; Name subscriber_;
Das RingTone rTone_; RingTone rTone_;
AddressBook aBook_;
PhoneNumber *lastDial_;
Objectives & void SetLastDialed(const PhoneNumber& p);
Outline void ShowNumber();
public: public:
Example –
LandlinePhone(const char *num, MobilePhone(const char *num,
Phone
const char *subs); const char *subs);
Hierarchy
void Call(const PhoneNumber *p); void Call(PhoneNumber *p);
Summary void Call(const Name& n);
void ReDial();
void Answer(); void Answer();
void SetRingTone(RingTone::RINGTONE r);
void AddContact(const char *num = 0,
const char *subs = 0);

friend ostream& operator<<(ostream& os, friend ostream& operator<<(ostream& os,


const LandlinePhone& p); const MobilePhone& p);
}; };

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Hierarchy of Phones

Module 24

Partha Pratim
Das

Objectives &
Outline

Example –
Phone
Hierarchy

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


MobilePhone ISA LandlinePhone

Module 24 Base Class Derived Class


class LandlinePhone { class MobilePhone : public LandlinePhone {
Partha Pratim protected: protected:
Das PhoneNumber number_; //PhoneNumber number_;
Name subscriber_; //Name subscriber_;
RingTone rTone_; //RingTone rTone_;
Objectives & AddressBook aBook_;
Outline PhoneNumber *lastDial_;
void SetLastDialed(const PhoneNumber& p);
Example –
void ShowNumber();
Phone
public: public:
Hierarchy
LandlinePhone(const char *num, MobilePhone(const char *num,
Summary const char *subs) : const char *subs) :
number_(num), subscriber_(subs), LandlinePhone(num, subs), // Base ctor
rTone_() {} lastDial_(0) {}

void Call(const PhoneNumber *p); void Call(const PhoneNumber *p); // Override


void Call(const Name& n); // Overload
void Answer(); //void Answer();
void ReDial();
void SetRingTone(RingTone::RINGTONE r);
void AddContact(const char *num = 0,
const char *subs = 0);

friend ostream& operator<<(ostream& os, friend ostream& operator<< (ostream& os,


const LandlinePhone& p); const MobilePhone& p);
}; };

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


SmartPhone ISA MobilePhone

Module 24 Base Class Derived Class


class MobilePhone : public LandlinePhone { class SmartPhone : public MobilePhone {
Partha Pratim protected: protected:
Das //PhoneNumber number_; //PhoneNumber number_;
//Name subscriber_; //Name subscriber_;
//RingTone rTone_; //RingTone rTone_;
Objectives & AddressBook aBook_; //AddressBook aBook_;
Outline PhoneNumber *lastDial_; //PhoneNumber *lastDial_;
void SetLastDialed(const PhoneNumber& p); //void SetLastDialed(const PhoneNumber& p);
Example –
void ShowNumber(); //void ShowNumber();
Phone
unsigned int size_;
Hierarchy
void DisplayPhoto()
Summary public: public:
MobilePhone(const char *num, SmartPhone(const char *num,
const char *subs) : const char *subs) :
LandlinePhone(num, subs), // Base ctor MobilePhone(num, subs), // Base ctor
lastDial_(0) {} lastDial_(0) {}

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);
}; };

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Phone Hierarchy
class Phone { class MobilePhone : public LandlinePhone {
Module 24 public: protected:
virtual void Call(const PhoneNumber *p) AddressBook aBook_;
Partha Pratim = 0; PhoneNumber *lastDial_;
Das virtual void Answer() = 0; void SetLastDialed(const PhoneNumber& p);
virtual void ReDial() = 0; void ShowNumber();
}; public:
Objectives & class LandlinePhone: public Phone { MobilePhone(const char *num,
Outline void ReDial() const char *subs) :
{ cout << "Not implemented" << endl; } LandlinePhone(num, subs), // Base ctor
Example – lastDial_(0) {}
Phone protected: void Call(const PhoneNumber *p); // Override
Hierarchy PhoneNumber number_; void Call(const Name& n); // Overload
Name subscriber_; void ReDial();
Summary
RingTone rTone_; friend ostream& operator<< (ostream& os,
public: const MobilePhone& p);
LandlinePhone(const char *num, };
const char *subs) : class SmartPhone : public MobilePhone {
number_(num), subscriber_(subs), protected: unsigned int size_;
rTone_() {} void DisplayPhoto()
void Call(const PhoneNumber *p); public:
void Answer(); SmartPhone(const char *num,
friend ostream& operator<<(ostream& os, const char *subs) :
const LandlinePhone& p); MobilePhone(num, subs), // Base ctor
}; lastDial_(0) {}
void Call(const PhoneNumber *p); // Override
void Call(const Name& n); // Override
void ReDial(); // Override
friend ostream& operator<< (ostream& os,
const SmartPhone& p);
};
NPTEL MOOCs Programming in C++ Partha Pratim Das 15
Hierarchy of Phones

Module 24

Partha Pratim
Das

Objectives &
Outline

Example –
Phone
Hierarchy

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 16


Module Summary

Module 24

Partha Pratim Using the Phone Hierarchy as an example analyzed the


Das
design process with inheritance
Objectives &
Outline

Example –
Phone
Hierarchy

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 18


Module 25

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

Use & [email protected]


Examples

Summary
Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 25

Partha Pratim Explore restricted forms of inheritance (private and


Das
protected) in C++ and their semantic implications
Objectives &
Outline

Inheritance in
C++

private
Inheritance

protected
Inheritance

Visibility

Use &
Examples

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 25

Partha Pratim ISA Relationship


Das
Inheritance in C++
Objectives &
Outline
Semantics
Inheritance in
Data Members and Object Layout
C++ Member Functions
private Overriding
Inheritance
Overloading
protected
Inheritance protected Access
Visibility Constructor & Destructor
Use & Object Lifetime
Examples
Example – Phone Hierarchy
Summary
Inheritance in C++ (private)
Implemented-As Semantics

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Inheritance in C++: Semantics

Module 25 Derived ISA Base


Partha Pratim
Das

Objectives & class Base; // Base Class = Base


Outline class Derived: public Base; // Derived Class = Derived
Inheritance in
C++ Use keyword public after class name to denote
private inheritance
Inheritance

protected
Name of the Base class follow the keyword
Inheritance

Visibility

Use &
Examples

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Inheritance Exercise: What is the output?

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 };

Visibility int main() {


D d;
Use &
Examples return 0;
}
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Inheritance Exercise: What is the output?

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 };

Visibility int main() {


D d;
Use &
Examples return 0;
}
Summary

Output:

B C D
~D ~C ~B

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


private Inheritance

Module 25 private Inheritance


Definition
Partha Pratim
Das class Base;
class Derived: private Base;
Objectives & Use keyword private after class name
Outline
Name of the Base class follow the keyword
Inheritance in private inheritance does not mean generalization / specialization
C++

private
Inheritance • Private inheritance means nothing during software design, only during
protected software implementation
Inheritance

Visibility • Private inheritance means is-implemented-in-terms of. It’s usually in-


ferior to composition, but it makes sense when a derived class needs access
Use &
Examples
to protected base class members or needs to redefine inherited virtual functions

Summary – Scott Meyers in Item 32, Effective C++ (3rd. Edition)

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


private Inheritance
public Inheritance private Inheritance
Module 25
class Person {...}; class Person { ... };
Partha Pratim
Das class Student: class Student: // inheritance is now private
public Person {...}; private Person { ... };

Objectives & // anyone can eat


// anyone can eat
Outline void eat(const Person& p);
void eat(const Person& p);
Inheritance in // only students study
C++ // only students study
void study(const Student& s); void study(const Student& s);
private
Person p; // p is a Person Person p; // p is a Person
Inheritance

protected Student s; // s is a Student Student s; // s is a Student


Inheritance
eat(p); // fine, p is a Person eat(p); // fine, p is a Person
Visibility
eat(s); // fine, s is a Student, eat(s); // error! a Student isn’t a Person
Use &
// and a Student is-a Person
Examples

Summary study(s); // fine

study(p); // error! p isn’t a Student

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


protected Inheritance

Module 25 protected Inheritance


Definition
Partha Pratim
Das class Base;
class Derived: protected Base;
Objectives & Use keyword protected after class name
Outline
Name of the Base class follow the keyword
Inheritance in protected inheritance does not mean generalization / specialization
C++

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Visibility across Access and Inheritance

Module 25 Visibility Matrix


Partha Pratim Inheritance
Das
public protected private
Objectives &
Visibility
Outline
public public protected private
Inheritance in
protected protected protected private
C++
private private private private
private
Inheritance

protected
Inheritance

Visibility

Use &
Examples

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Inheritance Exercise: What is the output?

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 };

Visibility int main() {


D d;
Use &
Examples return 0;
}
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Inheritance Exercise: What is the output?

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 };

Visibility int main() {


D d;
Use &
Examples return 0;
}
Summary

Output:

B C B C D
~D ~C ~B ~C ~B

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Inheritance Exercise: Access Rights
Inaccessible Members Accessible Members
Module 25 class A { void f(A& a,
private: int x; B& b, C& c, D& d,
Partha Pratim protected: int y; E& e, F& f, G& g) {
Das public: int z; a.z;
};
class B : public A { b.z;
Objectives & private: int u; b.w;
Outline protected: int v;
public: int w; void f() { x; } c.w;
Inheritance in };
C++ class C: protected A { d.w;
private: int u;
private
protected: int v; e.z;
Inheritance
public: int w; void f() { x; } e.w;
protected };
Inheritance class D: private A { f.w;
private: int u;
Visibility protected: int v; g.w;
public: int w; void f() { x; } }
Use & };
Examples class E : public B {
public: void f() { x; u; }
Summary };
class F : public C {
public: void f() { x; u; }
};
class G : public D {
public: void f() { x; y; z; u; }
};

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Car HAS–A Engine:
Composition OR private Inheritance?
Simple Composition private Inheritance
Module 25
#include <iostream> #include <iostream>
using namespace std; using namespace std;
Partha Pratim
Das
class Engine { class Engine {
public: public:
Objectives & Engine(int numCylinders) { } Engine(int numCylinders) { }
Outline // Starts this Engine // Starts this Engine
void start() { } void start() { }
Inheritance in }; };
C++
class Car { class Car : private Engine { // Car has-a Engine
private public: public:
Inheritance // Initializes this Car with 8 cylinders // Initializes this Car with 8 cylinders
protected Car() : e_(8) { } Car() : Engine(8) { }
Inheritance
// Start this Car by starting its Engine // Start this Car by starting its Engine
Visibility void start() { e_.start(); } using Engine::start;
private:
Use & Engine e_; // Car has-a Engine
Examples }; };

Summary int main() { int main() {


Car c; Car c;

c.start(); c.start();

return 0; return 0;
} }

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


private Inheritance

Module 25 Use composition when you can, private inheritance when


Partha Pratim you have to
Das

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)

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Module Summary

Module 25

Partha Pratim Introduced restricted forms of inheritance and protected


Das
specifier
Objectives &
Outline Discussed how private inheritance is used for
Inheritance in Implemented-As Semantics
C++

private
Inheritance

protected
Inheritance

Visibility

Use &
Examples

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 16


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Module 26

Partha Pratim
Das Module 26: Programming in C++
Objectives &
Outline
Dynamic Binding (Polymorphism): Part 1
Casting
Upcast &
Downcast

Static and Partha Pratim Das


Dynamic
Binding
Department of Computer Science and Engineering
Summary Indian Institute of Technology, Kharagpur
[email protected]

Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 26

Partha Pratim Understand Casting in a class hierarchy


Das
Understand Static and Dynamic Binding
Objectives &
Outline

Casting
Upcast &
Downcast

Static and
Dynamic
Binding

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 26

Partha Pratim Casting


Das
Upcast & Downcast
Objectives &
Outline
Static and Dynamic Binding
Casting
Upcast &
Downcast

Static and
Dynamic
Binding

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Casting: Basic Rules

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;

double result = d / i; // i is cast to double and used


Objectives &
Outline
Casting can be implicit or explicit
Casting
int i = 3;
Upcast &
Downcast double d = 2.5;

Static and double *p = &d;


Dynamic
Binding d = i; // implicit

Summary i = d; // implicit -- // warning C4244: ’=’ : conversion from ’double’ to ’int’,


// possible loss of data
i = (int)d; // explicit

i = p; // error C2440: ’=’ : cannot convert from ’double *’ to ’int’


i = (int)p; // explicit

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Casting: Basic Rules

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’

p = q; // error C2440: ’=’ : cannot convert from ’main::B *’ to ’main::A *’

q = p; // error C2440: ’=’ : cannot convert from ’main::A *’ to ’main::B *’

p = (A*)&b; // Forced -- Okay


q = (B*)&a; // Forced -- Okay

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Casting: Basic Rules

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;

cout << p->i << endl; // prints -858993459 ------------- GARBAGE


cout << q->d << endl; // prints -9.25596e+061 ------------- GARBAGE

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Casting on a Hierarchy

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

Static and pv = pa; // okay ------------------------------------------------- // Lose the type


Dynamic pv = pb; // okay ------------------------------------------------- // Lose the type
Binding
pa = pv; // error C2440: ’=’ : cannot convert from ’void *’ to ’A *’
Summary pb = pv; // error C2440: ’=’ : cannot convert from ’void *’ to ’B *’

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Casting on a Hierarchy

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;

cout << pa->dataA_ << endl; // prints 3


// cout << pa->dataB_ << endl; // error C2039: ’dataB_’ : is not a member of ’A’

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Static and Dynamic Binding

#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 };

Casting class D: public B {


Upcast & public:
Downcast void f() { cout << "D::f()" << endl; }
Static and virtual void g() { cout << "D::g()" << endl; }
Dynamic };
Binding
int main() { pb->f(); // B::f() -- Static Binding
Summary B b; pb->g(); // B::g() -- Dynamic Binding
D d; pd->f(); // B::f() -- Static Binding
pd->g(); // D::g() -- Dynamic Binding
B *pb = &b;
B *pd = &d; // UPCAST rb.f(); // B::f() -- Static Binding
rb.g(); // B::g() -- Dynamic Binding
B &rb = b; rd.f(); // B::f() -- Static Binding
B &rd = d; // UPCAST rd.g(); // D::g() -- Dynamic Binding

b.f(); // B::f() return 0;


b.g(); // B::g() }
d.f(); // D::f()
d.g(); // D::g()

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Module Summary

Module 26

Partha Pratim Introduced casting and discussed the notions of upcast


Das
and downcast
Objectives &
Outline Introduced Static and Dynamic Binding
Casting
Upcast &
Downcast

Static and
Dynamic
Binding

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Module 27

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 27

Partha Pratim Understand Static and Dynamic Binding


Das
Understand Polymorphic Type
Objectives &
Outline

Binding
Types
Static Binding
Dynamic
Binding

Polymorphic
Type

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 27

Partha Pratim Binding


Das
Types
Objectives & Static Binding
Outline
Dynamic Binding
Binding
Types Polymorphic Type
Static Binding
Dynamic
Binding

Polymorphic
Type

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Type of an Object

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
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Static and Dynamic Binding

Module 27 Static binding (early binding): When a function invocation


Partha Pratim binds to the function definition based on the static type of
Das
objects
Objectives &
Outline
This is done at compile-time
Binding Normal function calls, overloaded function calls, and overloaded
Types
Static Binding operators are examples of static binding
Dynamic
Binding
Dynamic binding (late binding): When a function invocation
Polymorphic
Type binds to the function definition based on the dynamic type of
Summary objects
This is done at run-time
Function pointers, Virtual functions are examples of late binding

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Static Binding

Module 27 Inherited Method Overridden Method

Partha Pratim #include<iostream> #include<iostream>


Das using namespace std; using namespace std;
class B { public: class B { public:
void f() {} void f() { }
Objectives & }; };
Outline class D : public B { public: class D : public B { public:
void g() {} // new function void f() { }
Binding
}; };
Types int main() { int main() {
Static Binding
B b; B b;
Dynamic
Binding D d; D d;

Polymorphic b.f(); // B::f() b.f(); // B::f()


Type d.f(); // B::f() ----- Inherited d.f(); // D::f() ----- Overridden
d.g(); // D::g() ----- Added // masks the base class function
Summary } }

• 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Member Functions – Overrides and Overloads:
RECAP (Module 22)
Module 27 Inheritance Override & Overload

Partha Pratim class B { // Base Class class B { // Base Class


Das public: public:
void f(int i); void f(int);
void g(int i); void g(int i);
Objectives & };
};
Outline class D: public B { // Derived Class
class D: public B { // Derived Class
public: public:
Binding
// Inherits B::f(int) // Inherits B::f(int)
Types
// Inherits B::g(int) void f(int); // Overrides B::f(int)
Static Binding
void f(string&); // Overloads B::f(int)
Dynamic
Binding // Inherits B::g(int)
void h(int i); // Adds D::h(int)
Polymorphic }; };
Type
B b; B b;
Summary D d;
D d;

b.f(1); // Calls B::f(int) b.f(1); // Calls B::f(int)


b.g(2); // Calls B::g(int) b.g(2); // Calls B::g(int)

d.f(3); // Calls B::f(int) d.f(3); // Calls D::f(int)


d.g(4); // Calls B::g(int) d.g(4); // Calls B::g(int)

d.f("red"); // Calls D::f(string&)


d.h(5); // Calls D::h(int)
• D::f(int) overrides B::f(int)
• D::f(string) overloads B::f(int)

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


using Construct – Avoid Method Hiding

Module 27 #include<iostream>
using namespace std;
Partha Pratim class A { public:
Das void f() {}
};

Objectives & class B : public A {


Outline // To overload, rather than hide the base class function f()
// is introduced into the scope of B with a using declaration
Binding
using A::f;
Types void f(int) { }
Static Binding };
Dynamic
Binding
int main() {
Polymorphic B b; // function calls resolved at compile time
Type
b.f(3); // B::f(int)
Summary b.f(); // A::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

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Dynamic Binding

Module 27 Non-Virtual Method Virtual Method

Partha Pratim #include<iostream> #include<iostream>


Das using namespace std; using namespace std;
class B { public: class B { public:
void f() { } virtual void f() { }
Objectives & }; };
Outline class D : public B { public: class D : public B { public:
void f() { } virtual void f() { }
Binding
}; };
Types int main() { int main() {
Static Binding
B b; B b;
Dynamic
Binding D d; D d;

Polymorphic B *p; B *p;


Type
p = &b; p->f(); // B::f() p = &b; p->f(); // B::f()
Summary p = &d; p->f(); // B::f() p = &d; p->f(); // D::f()
} }

• 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Static and Dynamic Binding:
RECAP (Module 26)
#include <iostream>
Module 27
using namespace std;
Partha Pratim class B {
Das public:
void f() { cout << "B::f()" << endl; }
Objectives & virtual void g() { cout << "B::g()" << endl; }
Outline };

Binding class D: public B {


Types public:
Static Binding void f() { cout << "D::f()" << endl; }
Dynamic virtual void g() { cout << "D::g()" << endl; }
Binding };
Polymorphic
Type int main() { pb->f(); // B::f() -- Static Binding
B b; pb->g(); // B::g() -- Dynamic Binding
Summary
D d; pd->f(); // B::f() -- Static Binding
pd->g(); // D::g() -- Dynamic Binding
B *pb = &b;
B *pd = &d; // UPCAST rb.f(); // B::f() -- Static Binding
rb.g(); // B::g() -- Dynamic Binding
B &rb = b; rd.f(); // B::f() -- Static Binding
B &rd = d; // UPCAST rd.g(); // D::g() -- Dynamic Binding

b.f(); // B::f() return 0;


b.g(); // B::g() }
d.f(); // D::f()
d.g(); // D::g()

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Polymorphic Type: Virtual Functions

Module 27 Dynamic binding is possible only for pointer and reference


Partha Pratim data types and for member functions that are declared as
Das
virtual in the base class.
Objectives &
Outline These are called Virtual Functions
Binding If a member function is declared as virtual, it can be
Types
Static Binding overridden in the derived class
Dynamic
Binding
If a member function is not virtual and it is re-defined in
Polymorphic
Type the derived class then the latter definition hides the former
Summary one
Any class containing a virtual member function – by
definition or by inheritance – is called a Polymorphic Type
A hierarchy may be polymorphic or non-polymorphic
A non-polymorphic hierarchy has little value

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Polymorphism Rule
#include <iostream>
Module 27 using namespace std;
class A { public:
Partha Pratim void f() { cout << "A::f()" << endl; } // Non-Virtual
Das virtual void g() { cout << "A::g()" << endl; } // Virtual
void h() { cout << "A::h()" << endl; } // Non-Virtual
};
Objectives &
class B : public A { public:
Outline
void f() { cout << "B::f()" << endl; } // Non-Virtual
Binding void g() { cout << "B::g()" << endl; } // Virtual
virtual void h() { cout << "B::h()" << endl; } // Virtual
Types
};
Static Binding
Dynamic
class C : public B { public:
Binding void f() { cout << "C::f()" << endl; } // Non-Virtual
void g() { cout << "C::g()" << endl; } // Virtual
Polymorphic void h() { cout << "C::h()" << endl; } // Virtual
Type };
Summary
int main() { B *q = new C; A *p = q; A::f()
C::g()
p->f(); A::h()
p->g(); B::f()
p->h(); C::g()
C::h()
q->f();
q->g();
q->h();

return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Module Summary

Module 27

Partha Pratim Static and Dynamic Binding are discussed in depth


Das
Polymorphic type introduced
Objectives &
Outline

Binding
Types
Static Binding
Dynamic
Binding

Polymorphic
Type

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Module 28

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 28

Partha Pratim Understand why destructor must be virtual in a class


Das
hierarchy
Objectives &
Outline Learn to work with class hierarchy
Virtual
Destructor

Pure Virtual
Function

Abstract Base
Class

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 28

Partha Pratim Virtual Destructor


Das
Pure Virtual Function
Objectives &
Outline Abstract Base Class
Virtual
Destructor

Pure Virtual
Function

Abstract Base
Class

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Virtual Destructor

Module 28 #include <iostream>


using namespace std;
Partha Pratim
Das class B {
int data_;
public:
Objectives &
B(int d) :data_(d) { cout << "B()" << endl; }
Outline
~B() { cout << "~B()" << endl; }
Virtual virtual void Print() { cout << data_; }
Destructor };
class D: public B {
Pure Virtual int *ptr_;
Function public:
D(int d1, int d2) :B(d1), ptr_(new int(d2)) { cout << "D()" << endl; }
Abstract Base ~D() { cout << "~D()" << endl; delete ptr_; }
Class void Print() { B::Print(); cout << " " << *ptr_; }
};
Summary int main() { Output:
B *p = new B(2); B()
B *q = new D(3, 5); B()
D()
p->Print(); cout << endl; 2
q->Print(); cout << endl; 3 5
~B()
delete p; ~B()
delete q;
Destructor of d (type D) not called!
return 0;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Virtual Destructor

Module 28 #include <iostream>


using namespace std;
Partha Pratim
Das class B {
int data_;
public:
Objectives &
B(int d) :data_(d) { cout << "B()" << endl; }
Outline
virtual ~B() { cout << "~B()" << endl; } // Destructor made virtual
Virtual virtual void Print() { cout << data_; }
Destructor };
class D: public B {
Pure Virtual int *ptr_;
Function public:
D(int d1, int d2) :B(d1), ptr_(new int(d2)) { cout << "D()" << endl; }
Abstract Base ~D() { cout << "~D()" << endl; delete ptr_; }
Class void Print() { B::Print(); cout << " " << *ptr_; }
};
Summary int main() { Output:
B *p = new B(2); B()
B *q = new D(3, 5); B()
D()
p->Print(); cout << endl; 2
q->Print(); cout << endl; 3 5
~B()
delete p; ~D()
delete q; ~B()

return 0; Destructor of d (type D) is called!


}

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Virtual Destructor

Module 28 If the destructor is not virtual in a polymorphic hierarchy,


Partha Pratim it leads to Slicing
Das
Destructor must be declared virtual in the base class
Objectives &
Outline

Virtual
Destructor

Pure Virtual
Function

Abstract Base
Class

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Hierarchy of Shapes

Module 28

Partha Pratim
Das

Objectives &
Outline

Virtual
Destructor

Pure Virtual
Function

Abstract Base
Class

Summary

We want to have a polymorphic draw() function for the hierarchy


draw() will be overridden in every class based on the drawing algorithms
What is the draw() function for the root Shapes class?

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Pure Virtual Function

Module 28 For the polymorphic hierarchy of Shapes, we need draw() to be


Partha Pratim a virtual function
Das
draw() must be a member of Shapes class for polymorphic
Objectives &
Outline
dispatch to work
Virtual
Destructor
But we cannot define the body of draw() function for the root
Shapes class as we do not have an algorithm to draw an
Pure Virtual
Function arbitrary share. In fact, we cannot even have a representation
Abstract Base for shapes in general!
Class

Summary Pure Virtual Function solves the problem


A Pure Virtual Function has a signature but no body!

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Abstract Base Class

Module 28 A class containing at least one Pure Virtual Function is called


Partha Pratim an Abstract Base Class
Das
Pure Virtual Functions may be inherited or defined in the class
Objectives &
Outline No instance can be created for an Abstract Base Class
Virtual
Destructor Naturally it does not have a constructor or the destructor
Pure Virtual
Function An Abstract Base Class, however, may have other virtual
Abstract Base (non-pure) and non-virtual member functions as well as data
Class
members
Summary
Data members in an Abstract Base Class should be protected.
Of course, private and public data are also allowed
Member functions in an Abstract Base Class should be public.
Of course, private and protected methods are also allowed
A Concrete Class must override and implement all Pure Virtual
Functions so that it can be instantiated
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Shape Hierarchy
#include <iostream>
Module 28 using namespace std;

Partha Pratim class Shapes { public: // Abstract Base Class


Das virtual void draw() = 0; // Pure Virtual Function
};
class Polygon: public Shapes { // Concrete Class
Objectives &
void draw() { cout << "Polygon: Draw by Triangulation" << endl; }
Outline
};
Virtual class ClosedConics : public Shapes { // Abstract Base Class
Destructor // draw() inherited - Pure Virtual
};
Pure Virtual class Triangle : public Polygon { public: // Concrete Class
Function void draw() { cout << "Triangle: Draw by Lines" << endl; }
};
Abstract Base class Quadrilateral : public Polygon { public: // Concrete Class
Class void draw() { cout << "Quadrilateral: Draw by Lines" << endl; }
};
Summary class Circle : public ClosedConics { public: // Concrete Class
void draw() { cout << "Circle: Draw by Breshenham Algorithm" << endl; }
};
class Ellipse : public ClosedConics { public: // Concrete Class
void draw() { cout << "Ellipse: Draw by ..." << endl; }
};
int main() {
Shapes *arr[] = { new Triangle, new Quadrilateral, new Circle, new Ellipse };

for (int i = 0; i < sizeof(arr) / sizeof(Shapes *); ++i) arr[i]->draw();


// ...
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Shape Hierarchy

Module 28 int main() {


Shapes *arr[] = { new Triangle, new Quadrilateral, new Circle, new Ellipse };
Partha Pratim
Das for (int i = 0; i < sizeof(arr) / sizeof(Shapes *); ++i) arr[i]->draw();
// ...
return 0;
Objectives & }
Outline -----
Output:
Virtual
Destructor
Triangle: Draw by Lines
Pure Virtual Quadrilateral: Draw by Lines
Function Circle: Draw by Breshenham Algorithm
Ellipse: Draw by ...
Abstract Base
Class

Summary
Instances for class Shapes and class ClosedConics
cannot be created

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Shape Hierarchy:
A Pure Virtual Function may have a body!
#include <iostream>
Module 28 using namespace std;
class Shapes { public: // Abstract Base Class
Partha Pratim virtual void draw() = 0 // Pure Virtual Function
Das { cout << "Shapes: Init Brush" << endl; }
};
class Polygon: public Shapes { // Concrete Class
Objectives &
void draw() { Shapes::draw(); cout << "Polygon: Draw by Triangulation" << endl; }
Outline
};
Virtual class ClosedConics : public Shapes { // Abstract Base Class
Destructor // draw() inherited - Pure Virtual
};
Pure Virtual class Triangle : public Polygon { public: // Concrete Class
Function void draw() { Shapes::draw(); cout << "Triangle: Draw by Lines" << endl; }
};
Abstract Base class Quadrilateral : public Polygon { public: // Concrete Class
Class void draw() { Shapes::draw(); cout << "Quadrilateral: Draw by Lines" << endl; }
};
Summary class Circle : public ClosedConics { public: // Concrete Class
void draw() { Shapes::draw(); cout << "Circle: Draw by Breshenham Algorithm" << endl; }
};
class Ellipse : public ClosedConics { public: // Concrete Class
void draw() { Shapes::draw(); cout << "Ellipse: Draw by ..." << endl; }
};
int main() {
Shapes *arr[] = { new Triangle, new Quadrilateral, new Circle, new Ellipse };

for (int i = 0; i < sizeof(arr) / sizeof(Shapes *); ++i) arr[i]->draw();


// ...
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Shape Hierarchy

Module 28 int main() {


Shapes *arr[] = { new Triangle, new Quadrilateral, new Circle, new Ellipse };
Partha Pratim
Das for (int i = 0; i < sizeof(arr) / sizeof(Shapes *); ++i) arr[i]->draw();
// ...
return 0;
Objectives & }
Outline -----
Output:
Virtual
Destructor
Shapes: Init Brush
Pure Virtual Triangle: Draw by Lines
Function Shapes: Init Brush
Quadrilateral: Draw by Lines
Abstract Base Shapes: Init Brush
Class Circle: Draw by Breshenham Algorithm
Shapes: Init Brush
Summary Ellipse: Draw by ...

Instances for class Shapes and class ClosedConics


cannot be created

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Module Summary

Module 28

Partha Pratim Discussed why destructors must be virtual


Das
Introduced Pure Virtual Functions
Objectives &
Outline Introduced Abstract Base Class
Virtual
Destructor

Pure Virtual
Function

Abstract Base
Class

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Module 29

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

Summary Department of Computer Science and Engineering


Indian Institute of Technology, Kharagpur
[email protected]

Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 29

Partha Pratim Understand design with class hierarchy


Das

Objectives &
Outline

Binding:
Exercise

Staff Salary
Processing
C Solution

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 29

Partha Pratim Binding Exercise


Das
Staff Salary Processing
Objectives &
Outline
C Solution
Binding:
C++ Solution
Exercise Non-Polymorphic Hierarchy
Staff Salary Polymorphic Hierarchy
Processing
Polymorphic Hierarchy (Flexible)
C Solution

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Binding: Exercise
// Class Definitions // Application Codes
Module 29 A a;
class A { public:
Partha Pratim virtual void f(int) { } B b;
Das virtual void g(double) { } C c;
int h(A *) { }
Objectives & }; A *pA;
Outline
class B: public A { public: B *pB;
Binding: void f(int) { }
Exercise
virtual int h(B *) { }
Staff Salary };
Processing
class C: public B { public:
C Solution
void g(double) { }
Summary int h(B *) { }
};

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Binding: Exercise
// Class Definitions // Application Codes
Module 29 A a;
class A { public:
Partha Pratim virtual void f(int) { } B b;
Das virtual void g(double) { } C c;
int h(A *) { }
Objectives & }; A *pA;
Outline
class B: public A { public: B *pB;
Binding: void f(int) { }
Exercise
virtual int h(B *) { }
Staff Salary };
Processing
class C: public B { public:
C Solution
void g(double) { }
Summary int h(B *) { }
};

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Staff Salary Processing:
Problem Statement
Module 29 An organization needs to develop a salary processing application
Partha Pratim for its staff
Das
At present it has an engineering division only where Engineers
Objectives &
Outline
and Managers work. Every Engineer reports to some Manager.
Binding:
Every Manager can also work like an Engineer
Exercise
The logic for processing salary for Engineers and Managers are
Staff Salary
Processing different as they have different salary heads
C Solution

Summary In future, it may add Directors to the team. Then every


Manager will report to some Director. Every Director could also
work like a Manager
The logic for processing salary for Directors will also be distinct
Further, in future it may open other divisions, like Sales division,
and expand the workforce
Make a suitable extensible design
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
C Solution: Function Switch
Engineer + Manager
Module 29 How to represent Engineers and Managers?
Partha Pratim
Das
Collection of structs

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

Summary How to model variations in salary processing algorithms?


struct-specific 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: Function Switch
Engineer + Manager
Module 29 #include <stdio.h>
#include <string.h>
Partha Pratim
Das typedef enum E_TYPE { Er, Mgr } E_TYPE;

typedef struct Engineer { char *name_; } Engineer;


Objectives & Engineer *InitEngineer(const char *name) { Engineer *e = (Engineer *)malloc(sizeof(Engineer));
Outline e->name_ = strdup(name); return e;
}
Binding:
void ProcessSalaryEngineer(Engineer *e) {
Exercise
printf("%s: Process Salary for Engineer\n", e->name_);
Staff Salary }
Processing typedef struct Manager { char *name_; Engineer *reports_[10]; } Manager;
Manager *InitManager(const char *name) { Manager *m = (Manager *)malloc(sizeof(Manager));
C Solution
m->name_ = strdup(name); return m;
Summary }
void ProcessSalaryManager(Manager *m) {
printf("%s: Process Salary for Manager\n", m->name_);
}
typedef struct Staff { E_TYPE type_;
union { Engineer *pE; Manager *pM; };
} Staff;

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


C Solution: Function Switch
Engineer + Manager
Module 29 int main() {
Staff allStaff[10];
Partha Pratim allStaff[0].type_ = Er;
Das allStaff[0].pE = InitEngineer("Rohit");
allStaff[1].type_ = Mgr;
allStaff[1].pM = InitManager("Kamala");
Objectives & allStaff[2].type_ = Mgr;
Outline allStaff[2].pM = InitManager("Rajib");
allStaff[3].type_ = Er;
Binding:
allStaff[3].pE = InitEngineer("Kavita");
Exercise
allStaff[4].type_ = Er;
Staff Salary allStaff[4].pE = InitEngineer("Shambhu");
Processing
for (int i = 0; i < 5; ++i) {
C Solution
E_TYPE t = allStaff[i].type_;
Summary if (t == Er) ProcessSalaryEngineer(allStaff[i].pE);
else if (t == Mgr) ProcessSalaryManager(allStaff[i].pM);
else printf("Invalid Staff Type\n");
}
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

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


C Solution: Function Switch
Engineer + Manager + Director
Module 29 How to represent Engineers, Managers, and Directors?
Partha Pratim
Das
Collection of structs

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

Summary How to model variations in salary processing algorithms?


struct-specific functions
How to invoke the correct algorithm for a correct employee
type?
Function switch
Function pointers

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


C Solution: Function Switch
Engineer + Manager + Director
Module 29 #include <stdio.h>
#include <string.h>
Partha Pratim
Das typedef enum E_TYPE { Er, Mgr, Dir } E_TYPE;

typedef struct Engineer { char *name_; } Engineer;


Objectives & Engineer *InitEngineer(const char *name) { Engineer *e = (Engineer *)malloc(sizeof(Engineer));
Outline e->name_ = strdup(name); return e;
}
Binding:
void ProcessSalaryEngineer(Engineer *e) {
Exercise
printf("%s: Process Salary for Engineer\n", e->name_);
Staff Salary }
Processing typedef struct Manager { char *name_; Engineer *reports_[10]; } Manager;
Manager *InitManager(const char *name) { Manager *m = (Manager *)malloc(sizeof(Manager));
C Solution
m->name_ = strdup(name); return m;
Summary }
void ProcessSalaryManager(Manager *m) {
printf("%s: Process Salary for Manager\n", m->name_);
}
typedef struct Director { char *name_; Manager *reports_[10]; } Director;
Director *InitDirector(const char *name) { Director *d = (Director *)malloc(sizeof(Director));
d->name_ = strdup(name); return d;
}
void ProcessSalaryDirector(Director *d) {
printf("%s: Process Salary for Director\n", d->name_);
}
typedef struct Staff { E_TYPE type_;
union { Engineer *pE; Manager *pM; Director *pD; };
} Staff;

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


C Solution: Function Switch
Engineer + Manager + Director
int main() { Staff allStaff[10];
Module 29 allStaff[0].type_ = Er;
allStaff[0].pE = InitEngineer("Rohit");
Partha Pratim allStaff[1].type_ = Mgr;
Das allStaff[1].pM = InitManager("Kamala");
allStaff[2].type_ = Mgr;
allStaff[2].pM = InitManager("Rajib");
Objectives & allStaff[3].type_ = Er;
Outline allStaff[3].pE = InitEngineer("Kavita");
Binding: allStaff[4].type_ = Er;
Exercise allStaff[4].pE = InitEngineer("Shambhu");
allStaff[5].type_ = Dir;
Staff Salary allStaff[5].pD = InitDirector("Ranjana");
Processing
C Solution for (int i = 0; i < 6; ++i) {
E_TYPE t = allStaff[i].type_;
Summary if (t == Er) ProcessSalaryEngineer(allStaff[i].pE);
else if (t == Mgr) ProcessSalaryManager(allStaff[i].pM);
else if (t == Dir) ProcessSalaryDirector(allStaff[i].pD);
else printf("Invalid Staff Type\n");
}
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
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
C Solution: Advantages and Disadvantages
Advantages:
Module 29
Solution exists!
Partha Pratim Code is well structured – has patterns
Das
Disadvantages:
Objectives &
Outline
Employee data has scope for better organization

Binding: No encapsulation for data


Exercise Duplication of fields across types of employees – possible to mix up
Staff Salary types for them (say, char * and string)
Processing Employee objects are created and initialized dynamically through
C Solution Init... functions. How to release the memory?
Summary
Types of objects are managed explicitly by E Type:
Difficult to extend the design – addition of a new type needs to:
Add new type code to enum E Type
Add a new pointer field in struct Staff for the new type
Add a new case (it-else) based on the new type
Error prone – developer has to decide to call the right processing
function for every type (ProcessSalaryManager for Mgr etc.)
Recommendation:
Use classes for encapsulation on a hierarchy
NPTEL MOOCs Programming in C++ Partha Pratim Das 13
Module Summary

Module 29

Partha Pratim Practiced exercise with binding – various mixed cases


Das
Started designing for a staff salary problem and worked
Objectives &
Outline out C solutions
Binding:
Exercise

Staff Salary
Processing
C Solution

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Module 30

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 30

Partha Pratim Understand design with class hierarchy


Das

Objectives &
Outline

Staff Salary
Processing
C Solution
C++ Solution
Non-
Polymorphic
Hierarchy
Polymorphic
Hierarchy
Polymorphic
Hierarchy
(Flexible)

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 30

Partha Pratim Staff Salary Processing


Das
C Solution
Objectives & C++ Solution
Outline
Non-Polymorphic Hierarchy
Staff Salary Polymorphic Hierarchy
Processing
C Solution Polymorphic Hierarchy (Flexible)
C++ Solution
Non-
Polymorphic
Hierarchy
Polymorphic
Hierarchy
Polymorphic
Hierarchy
(Flexible)

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Staff Salary Processing:
Problem Statement: RECAP (Module 29)
Module 30 An organization needs to develop a salary processing application
Partha Pratim for its staff
Das
At present it has an engineering division only where Engineers
Objectives &
Outline
and Managers work. Every Engineer reports to some Manager.
Staff Salary
Every Manager can also work like an Engineer
Processing
C Solution The logic for processing salary for Engineers and Managers are
C++ Solution
Non- different as they have different salary heads
Polymorphic
Hierarchy
Polymorphic In future, it may add Directors to the team. Then every
Hierarchy
Polymorphic Manager will report to some Director. Every Director could also
Hierarchy
(Flexible) work like a Manager
Summary
The logic for processing salary for Directors will also be distinct
Further, in future it may open other divisions, like Sales division,
and expand the workforce
Make a suitable extensible design
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
C Solution:
Engineer + Manager: RECAP (Module 29)
Module 30 How to represent Engineers and Managers?
Partha Pratim
Das
struct

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


C Solution: Advantages and Disadvantages
RECAP (Module 29)
Advantages:
Module 30
Solution exists!
Partha Pratim Code is well structured – has patterns
Das
Disadvantages:
Objectives &
Outline
Employee data has scope for better organization

Staff Salary No encapsulation for data


Processing Duplication of fields across types of employees – possible to mix up
C Solution types for them (say, char * and string)
C++ Solution
Non- Employee objects are created and initialized dynamically through
Polymorphic
Hierarchy Init... functions. How to release the memory?
Polymorphic
Hierarchy Types of objects are managed explicitly by E Type:
Polymorphic
Hierarchy
(Flexible) Difficult to extend the design – addition of a new type needs to:
Summary Add new type code to enum E Type
Add a new pointer field in struct Staff for the new type
Add a new case (it-else) based on the new type
Error prone – developer has to decide to call the right processing
function for every type (ProcessSalaryManager for Mgr etc.)
Recommendation:
Use classes for encapsulation on a hierarchy
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
C++ Solution: Non-Polymorphic Hierarchy
Engineer + Manager
Module 30

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;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


C++ Solution: Non-Polymorphic Hierarchy
Engineer + Manager
Module 30 Engineer e1("Rohit"), e2("Kavita"), e3("Shambhu");
Manager m1("Kamala"), m2("Rajib");
Partha Pratim Engineer *staff[] = { &e1, &m1, &m2, &e2, &e3 };
Das
Output:
Rohit: Process Salary for Engineer
Objectives & Kamala: Process Salary for Manager
Outline Rajib: Process Salary for Manager
Kavita: Process Salary for Engineer
Staff Salary
Shambhu: Process Salary for Engineer
Processing
C Solution
C++ Solution
Non-
Polymorphic
Hierarchy
Polymorphic
Hierarchy
Polymorphic
Hierarchy
(Flexible)

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


C++ Solution: Non-Polymorphic Hierarchy
Engineer + Manager + Director
Module 30

Partha Pratim
Das

Objectives & How to represent Engineers, Managers, and Directors?


Outline
Non-Polymorphic class hierarchy
Staff Salary
Processing How to initialize objects?
C Solution
C++ Solution
Non-
Constructor / Destructor
Polymorphic
Hierarchy How to have a collection of mixed objects?
Polymorphic
Hierarchy
Polymorphic
array of base class pointers
Hierarchy
(Flexible) How to model variations in salary processing algorithms?
Summary
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 10


C++ Solution: Non-Polymorphic Hierarchy
Engineer + Manager + Director
#include <iostream>
Module 30 #include <string>
using namespace std;
Partha Pratim
Das typedef enum E_TYPE { Er, Mgr, Dir };
class Engineer { protected: string name_; E_TYPE type_;
public: Engineer(const string& name, E_TYPE e = Er) : name_(name), type_(e) {}
Objectives &
E_TYPE GetType() { return type_; }
Outline
void ProcessSalary() { cout << name_ << ": Process Salary for Engineer" << endl; }
Staff Salary };
Processing class Manager : public Engineer { Engineer *reports_[10];
public: Manager(const string& name, E_TYPE e = Mgr) : Engineer(name, e) {}
C Solution
void ProcessSalary() { cout << name_ << ": Process Salary for Manager" << endl; }
C++ Solution
Non-
};
Polymorphic class Director : public Manager { Manager *reports_[10];
Hierarchy public: Director(const string& name) : Manager(name, Dir) {}
Polymorphic void ProcessSalary() { cout << name_ << ": Process Salary for Director" << endl; }
Hierarchy
};
Polymorphic
Hierarchy int main() { Engineer e1("Rohit"), e2("Kavita"), e3("Shambhu");
(Flexible) Manager m1("Kamala"), m2("Rajib"); Director d("Ranjana");
Engineer *staff[] = { &e1, &m1, &m2, &e2, &e3, &d };
Summary
for (int i = 0; i < sizeof(staff) / sizeof(Engineer*); ++i) {
E_TYPE t = staff[i]->GetType();
if (t == Er) staff[i]->ProcessSalary();
else if (t == Mgr) ((Manager *)staff[i])->ProcessSalary();
else if (t == Dir) ((Director *)staff[i])->ProcessSalary();
else cout << "Invalid Staff Type" << endl;
}
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 11
C++ Solution: Non-Polymorphic Hierarchy
Engineer + Manager + Director
Module 30 Engineer e1("Rohit"), e2("Kavita"), e3("Shambhu");
Manager m1("Kamala"), m2("Rajib"); Director d("Ranjana");
Partha Pratim Engineer *staff[] = { &e1, &m1, &m2, &e2, &e3, &d };
Das
Output:
Rohit: Process Salary for Engineer
Objectives & Kamala: Process Salary for Manager
Outline Rajib: Process Salary for Manager
Kavita: Process Salary for Engineer
Staff Salary
Shambhu: Process Salary for Engineer
Processing
Ranjana: Process Salary for Director
C Solution
C++ Solution
Non-
Polymorphic
Hierarchy
Polymorphic
Hierarchy
Polymorphic
Hierarchy
(Flexible)

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


C++ Solution: Non-Polymorphic Hierarchy:
Advantages and Disadvantages
Advantages:
Module 30
Data is encapsulated
Partha Pratim
Das Hierarchy factors common data members
Constructor / Destructor to manage lifetime
Objectives &
Outline struct-specific functions made member function (overridden)
Staff Salary E Type subsumed in class – no need for union
Processing
C Solution
Code reuse evidenced
C++ Solution Disadvantages:
Non-
Polymorphic
Hierarchy Types of objects are managed explicitly by E Type:
Polymorphic
Hierarchy Difficult to extend the design – addition of a new type needs to:
Polymorphic
Hierarchy Add new type code to enum E Type
(Flexible)
Application code need to have a new case (if-else) based on
Summary
the new type
Error prone because the application programmer has to cast to right
type to call ProcessSalary
Recommendation:
Use a polymorphic hierarchy with dynamic dispatch

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


C++ Solution: Polymorphic Hierarchy
Engineer + Manager + Director
Module 30

Partha Pratim
Das

Objectives & How to represent Engineers, Managers, and Directors?


Outline
Polymorphic class hierarchy
Staff Salary
Processing How to initialize objects?
C Solution
C++ Solution
Non-
Constructor / Destructor
Polymorphic
Hierarchy How to have a collection of mixed objects?
Polymorphic
Hierarchy
Polymorphic
array of base class pointers
Hierarchy
(Flexible) How to model variations in salary processing algorithms?
Summary
Member functions
How to invoke the correct algorithm for a correct employee type?
Virtual Functions

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


C++ Solution: Polymorphic Hierarchy
Engineer + Manager + Director
Module 30 #include <iostream>
#include <string>
Partha Pratim using namespace std;
Das
class Engineer { protected: string name_;
public: Engineer(const string& name) : name_(name) {}
Objectives & virtual void ProcessSalary() { cout << name_ << ": Process Salary for Engineer" << endl; }
Outline };
class Manager : public Engineer { Engineer *reports_[10];
Staff Salary
public: Manager(const string& name) : Engineer(name) {}
Processing
void ProcessSalary() { cout << name_ << ": Process Salary for Manager" << endl; }
C Solution };
C++ Solution
class Director : public Manager { Manager *reports_[10];
Non-
Polymorphic public: Director(const string& name) : Manager(name) {}
Hierarchy void ProcessSalary() { cout << name_ << ": Process Salary for Director" << endl; }
Polymorphic };
Hierarchy int main() { Engineer e1("Rohit"), e2("Kavita"), e3("Shambhu");
Polymorphic
Hierarchy Manager m1("Kamala"), m2("Rajib"); Director d("Ranjana");
(Flexible) Engineer *staff[] = { &e1, &m1, &m2, &e2, &e3, &d };
Summary for (int i = 0; i < sizeof(staff) / sizeof(Engineer*); ++i) staff[i]->ProcessSalary();

return 0;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


C++ Solution: Polymorphic Hierarchy
Engineer + Manager + Director
Module 30 Engineer e1("Rohit"), e2("Kavita"), e3("Shambhu");
Manager m1("Kamala"), m2("Rajib"); Director d("Ranjana");
Partha Pratim Engineer *staff[] = { &e1, &m1, &m2, &e2, &e3, &d };
Das
Output:
Rohit: Process Salary for Engineer
Objectives & Kamala: Process Salary for Manager
Outline Rajib: Process Salary for Manager
Kavita: Process Salary for Engineer
Staff Salary
Shambhu: Process Salary for Engineer
Processing
Ranjana: Process Salary for Director
C Solution
C++ Solution
Non-
Polymorphic
Hierarchy
Polymorphic
Hierarchy
Polymorphic
Hierarchy
(Flexible)

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 16


C++ Solution: Polymorphic Hierarchy:
Advantages and Disadvantages
Advantages:
Module 30
Data is fully encapsulated
Partha Pratim
Das Polymorphic Hierarchy removes the need for explicit E Type
Application code is independent of types in the system (virtual functions
Objectives &
Outline
manage types through polymorphic dispatch)
High Code reuse – code is short and simple
Staff Salary
Processing Disadvantages:
C Solution
C++ Solution Difficult to add an employee type that is not a part of this hierarchy (for
Non-
Polymorphic
example, employees of Sales Division
Hierarchy
Polymorphic Recommendation:
Hierarchy
Polymorphic Use an abstract base class for employees
Hierarchy
(Flexible)

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


C++ Solution: Polymorphic Hierarchy (Flexible)
Engineer + Manager + Director + Others
Module 30

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)

Summary array of base class pointers


How to model variations in salary processing algorithms?
Member functions
How to invoke the correct algorithm for a correct employee type?
Virtual Functions (Pure in Employee)

NPTEL MOOCs Programming in C++ Partha Pratim Das 18


C++ Solution: Polymorphic Hierarchy (Flexible)
Engineer + Manager + Director + Others
#include <iostream>
Module 30 #include <string>
using namespace std;
Partha Pratim
Das class Employee { protected: string name_;
public: virtual void ProcessSalary() = 0;
};
Objectives &
class Engineer: public Employee { public: Engineer(const string& name) { name_ = name; }
Outline
void ProcessSalary() { cout << name_ << ": Process Salary for Engineer" << endl; }
Staff Salary };
Processing class Manager : public Engineer { Engineer *reports_[10];
public: Manager(const string& name) : Engineer(name) {}
C Solution
void ProcessSalary() { cout << name_ << ": Process Salary for Manager" << endl; }
C++ Solution
Non-
};
Polymorphic class Director : public Manager { Manager *reports_[10];
Hierarchy public: Director(const string& name) : Manager(name) {}
Polymorphic void ProcessSalary() { cout << name_ << ": Process Salary for Director" << endl; }
Hierarchy
};
Polymorphic
Hierarchy class SalesExecutive : public Employee { public:
(Flexible) SalesExecutive(const string& name) { name_ = name; }
void ProcessSalary() { cout << name_ << ": Process Salary for Sales Executive" << endl; }
Summary
};
int main() {
Engineer e1("Rohit"), e2("Kavita"), e3("Shambhu");
Manager m1("Kamala"), m2("Rajib"); SalesExecutive s1("Hari"), s2("Bishnu");
Director d("Ranjana");
Employee *staff[] = { &e1, &m1, &m2, &e2, &s1, &e3, &d, &s2 };

for (int i = 0; i < sizeof(staff) / sizeof(Employee*); ++i) staff[i]->ProcessSalary();


return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 19
C++ Solution: Polymorphic Hierarchy (Flexible)
Engineer + Manager + Director + Others
Module 30 Engineer e1("Rohit"), e2("Kavita"), e3("Shambhu");
Manager m1("Kamala"), m2("Rajib"); SalesExecutive s1("Hari"), s2("Bishnu");
Partha Pratim Director d("Ranjana");
Das Employee *staff[] = { &e1, &m1, &m2, &e2, &s1, &e3, &d, &s2 };

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 20


C++ Solution: Polymorphic Hierarchy (Flexible):
Advantages and Disadvantages
Advantages:
Module 30
Data is fully encapsulated
Partha Pratim
Das Flexible Polymorphic Hierarchy makes addition of any class possible on the
hierarchy
Objectives &
Outline
Application code is independent of types in the system (virtual functions
manage types through polymorphic dispatch)
Staff Salary
Processing Maximum Code reuse – code is short and simple
C Solution
C++ Solution
Disadvantages:
Non-
Polymorphic
None in particular
Hierarchy
Polymorphic Recommendation:
Hierarchy
Polymorphic Enjoy the solution
Hierarchy
(Flexible)

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 21


Module Summary

Module 30

Partha Pratim Completed design for a staff salary problem using


Das
hierarchy and worked out extensible C++ solution
Objectives &
Outline

Staff Salary
Processing
C Solution
C++ Solution
Non-
Polymorphic
Hierarchy
Polymorphic
Hierarchy
Polymorphic
Hierarchy
(Flexible)

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 22


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 23


Module 31

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 31

Partha Pratim Understand Virtual Function Table for dynamic binding


Das
(polymorphic dispatch)
Objectives &
Outline

Staff Salary
Processing
C Solution
C++ Solution

Virtual
Function
Pointer Table

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 31

Partha Pratim Staff Salary Processing: RECAP


Das
C Solution using Function Pointers
Objectives & C++ Solution using Polymorphic Hierarchy
Outline
Comparison of C and C++ Solutions
Staff Salary
Processing Virtual Function Table for Polymorphic Dispatch
C Solution
C++ Solution

Virtual
Function
Pointer Table

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Staff Salary Processing:
Problem Statement: RECAP (Module 29)
Module 31 An organization needs to develop a salary processing application
Partha Pratim for its staff
Das
At present it has an engineering division only where Engineers
Objectives &
Outline
and Managers work. Every Engineer reports to some Manager.
Staff Salary
Every Manager can also work like an Engineer
Processing
C Solution The logic for processing salary for Engineers and Managers are
C++ Solution
different as they have different salary heads
Virtual
Function
Pointer Table In future, it may add Directors to the team. Then every
Summary
Manager will report to some Director. Every Director could also
work like a Manager
The logic for processing salary for Directors will also be distinct
Further, in future it may open other divisions, like Sales division,
and expand the workforce
Make a suitable extensible design
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
C Solution: Function Pointers
Engineer + Manager: RECAP (Module 29)
Module 31 How to represent Engineers, Managers, and Directors?
Partha Pratim
Das
struct

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


C Solution: Function Pointers
Engineer + Manager + Director
Module 31 #include <stdio.h>
#include <string.h>
Partha Pratim
Das typedef enum E_TYPE { Er, Mgr, Dir } E_TYPE;
typedef void (*psFuncPtr)(void *);

Objectives & typedef struct Engineer { char *name_; } Engineer;


Outline Engineer *InitEngineer(const char *name) { Engineer *e = (Engineer *)malloc(sizeof(Engineer));
e->name_ = strdup(name); return e;
Staff Salary
}
Processing
void ProcessSalaryEngineer(void *v) { Engineer *e = (Engineer *)v;
C Solution printf("%s: Process Salary for Engineer\n", e->name_);
C++ Solution
}
Virtual typedef struct Manager { char *name_; Engineer *reports_[10]; } Manager;
Function Manager *InitManager(const char *name) { Manager *m = (Manager *)malloc(sizeof(Manager));
Pointer Table m->name_ = strdup(name); return m;
}
Summary void ProcessSalaryManager(void *v) { Manager *m = (Manager *)v;
printf("%s: Process Salary for Manager\n", m->name_);
}
typedef struct Director { char *name_; Manager *reports_[10]; } Director;
Director *InitDirector(const char *name) { Director *d = (Director *)malloc(sizeof(Director));
d->name_ = strdup(name); return d;
}
void ProcessSalaryDirector(void *v) { Director *d = (Director *)v;
printf("%s: Process Salary for Director\n", d->name_);
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


C Solution: Function Pointers
Engineer + Manager + Director
Module 31 typedef struct Staff {
E_TYPE type_;
Partha Pratim void *p;
Das } Staff;
int main() {
psFuncPtr psArray[] = { ProcessSalaryEngineer,
Objectives & ProcessSalaryManager,
Outline ProcessSalaryDirector };
Staff Salary
Staff staff[] = { { Er, InitEngineer("Rohit") },
Processing
{ Mgr, InitEngineer("Kamala") },
C Solution { Mgr, InitEngineer("Rajib") },
C++ Solution
{ Er, InitEngineer("Kavita") },
Virtual { Er, InitEngineer("Shambhu") },
Function { Dir, InitEngineer("Ranjana") } };
Pointer Table
for (int i = 0; i < sizeof(staff) / sizeof(Staff); ++i)
Summary psArray[staff[i].type_](staff[i].p);

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


C++ Solution: Polymorphic Hierarchy: RECAP
Engineer + Manager + Director: (Module 30)
Module 31

Partha Pratim
Das

Objectives & How to represent Engineers, Managers, and Directors?


Outline
Polymorphic class hierarchy
Staff Salary
Processing How to initialize objects?
C Solution
C++ Solution
Constructor / Destructor
Virtual
Function How to have a collection of mixed objects?
Pointer Table
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?
Virtual Functions

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


C++ Solution: Polymorphic Hierarchy: RECAP
Engineer + Manager + Director: (Module 30)
Module 31 #include <iostream>
#include <string>
Partha Pratim using namespace std;
Das
class Engineer {
protected:
Objectives & string name_;
Outline public:
Engineer(const string& name) : name_(name) {}
Staff Salary
virtual void ProcessSalary()
Processing
{ cout << name_ << ": Process Salary for Engineer" << endl; }
C Solution };
C++ Solution
class Manager : public Engineer {
Virtual Engineer *reports_[10];
Function public:
Pointer Table Manager(const string& name) : Engineer(name) {}
void ProcessSalary()
Summary { cout << name_ << ": Process Salary for Manager" << endl; }
};
class Director : public Manager {
Manager *reports_[10];
public:
Director(const string& name) : Manager(name) {}
void ProcessSalary()
{ cout << name_ << ": Process Salary for Director" << endl; }
};

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


C++ Solution: Polymorphic Hierarchy: RECAP
Engineer + Manager + Director: (Module 30)
Module 31 int main() {
Engineer e1("Rohit");
Partha Pratim Engineer e2("Kavita");
Das Engineer e3("Shambhu");
Manager m1("Kamala");
Manager m2("Rajib");
Objectives & Director d("Ranjana");
Outline
Engineer *staff[] = { &e1, &m1, &m2, &e2, &e3, &d };
Staff Salary
Processing
for (int i = 0; i < sizeof(staff) / sizeof(Engineer*); ++i) staff[i]->ProcessSalary();
C Solution
C++ Solution
return 0;
Virtual }
Function
Pointer Table Output:
Rohit: Process Salary for Engineer
Summary 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


C and C++ Solutions: A Comparison
C Solution C++ Solution
Module 31 How to represent Engineers, How to represent Engineers,
Partha Pratim Managers, and Directors? Managers, and Directors?
Das
structs Polymorphic hierarchy
Objectives & How to initialize objects? How to initialize objects?
Outline

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 };

Staff staff[] = { Engineer e1("Rohit");


{ Er, InitEngineer("Rohit") }, Manager m1("Kamala");
{ Mgr, InitEngineer("Kamala") }, Director d("Ranjana");
{ Dir, InitEngineer("Ranjana") } }; Engineer *staff[] = { &e1, &m1, &d };

for (int i = 0; i < for(int i = 0; i <


sizeof(staff)/sizeof(Staff); ++i) sizeof(staff)/sizeof(Engineer*); ++i)
psArray[staff[i].type_](staff[i].p); staff[i]->ProcessSalary();
return 0; return 0;
} }
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Virtual Function Pointer Table
Base Class Derived Class
Module 31
class B { class D: public B {
Partha Pratim int i; int j;
Das public: public:
B(int i_): i(i_) {} D(int i_, int j_): B(i_), j(j_) {}
void f(int); // B::f(B*const, int) void f(int); // D::f(D*const, int)
Objectives & virtual void g(int); // B::g(B*const, int) void g(int); // D::g(D*const, int)
Outline } }
Staff Salary B b(100); D d(200, 500);
Processing
C Solution B *p = &b; B *p = &d;
C++ Solution

Virtual b Object Layout d Object Layout


Function
Pointer Table Object VFT Object VFT
Summary vft → 0 B::g(B*const, int) vft → 0 D::g(D*const, int)
B::i 100 B::i 200
D::j 500

Source Expression Compiled Expression Source Expression Compiled Expression


b.f(15); B::f(&b, 15); d.f(15); D::f(&d, 15);

p->f(25); B::f(p, 25); p->f(25); D::f(p, 25);

b.g(35); B::g(&b, 35); d.g(35); D::g(&d, 35);

p->g(45); p->vft[0](p, 45); p->g(45); p->vft[0](p, 45);

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Virtual Function Pointer Table

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Virtual Function Pointer Table
class A { public:
Module 31 virtual void f(int) { }
virtual void g(double) { }
Partha Pratim int h(A *) { } a Object Layout
Das };
class B: public A { public: Object VFT
void f(int) { } vft → 0 A::f(A*const, int)
Objectives & 1 A::g(A*const, double)
virtual int h(B *) { }
Outline
};
Staff Salary class C: public B { public:
void g(double) { } b Object Layout
Processing
int h(B *) { }
C Solution
}; Object VFT
C++ Solution
vft → 0 B::f(B*const, int)
Virtual A a; B b; C c; 1 A::g(A*const, double)
Function 2 B::h(B*const, B*)
Pointer Table A *pA; B *pB;

Summary c Object Layout


Source Expression Compiled Expression
pA->f(2); pA->vft[0](pA, 2); Object VFT
pA->g(3.2); pA->vft[1](pA, 3.2); vft → 0 B::f(B*const, int)
pA->h(&a); A::h(pA, &a); 1 C::g(C*const, double)
pA->h(&b); A::h(pA, &b); 2 C::h(C*const, B*)
pB->f(2); pB->vft[0](pB, 2);
pB->g(3.2); pB->vft[1](pB, 3.2);
pB->h(&a); pB->vft[2](pB, &a);
pB->h(&b); pB->vft[2](pB, &b);

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Module Summary

Module 31

Partha Pratim Leveraging an innovative solution to the Salary Processing


Das
Application in C using function pointers, we compare C
Objectives &
Outline
and C++ solutions to the problem
Staff Salary The new C solution is used to explain the mechanism for
Processing
C Solution
dynamic binding (polymorphic dispatch) based on virtual
C++ Solution
function tables
Virtual
Function
Pointer Table

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 16


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Module 32

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 32

Partha Pratim Understand casting in C and C++


Das

Objectives &
Outline

Casting
Upcast &
Downcast

Cast
Operators
const cast

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 32

Partha Pratim Casting: C-Style: RECAP


Das
Upcast & Downcast
Objectives &
Outline
Cast Operators in C++
Casting
const cast Operator
Upcast &
Downcast
static cast Operator
Cast
reinterpret cast Operator
Operators dynamic cast Operator
const cast

Summary typeid Operator

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Type Casting

Module 32 Why casting?


Casts are used to convert the type of an object, expression, function
Partha Pratim
Das argument, or return value to that of another type
(Silent) Implicit conversions
Objectives &
Outline The standard C++ conversions and user-defined conversions
Casting Explicit conversions
Upcast &
Downcast Type is needed for an expression that cannot be obtained through an
Cast implicit conversion more than one standard conversion creates an
Operators ambiguous situation
const cast

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;

double result = d / i; // i is cast to double and used


Objectives &
Outline
Casting can be implicit or explicit
Casting
int i = 3;
Upcast &
Downcast double d = 2.5;

Cast double *p = &d;


Operators
const cast d = i; // implicit

Summary i = d; // implicit -- // warning C4244: ’=’ : conversion from ’double’ to ’int’,


// possible loss of data
i = (int)d; // explicit

i = p; // error C2440: ’=’ : cannot convert from ’double *’ to ’int’


i = (int)p; // explicit

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Casting: C-Style:
RECAP (Module 26)
Module 32
(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’
Cast
Operators a = (A)b; // error C2440: ’type cast’ : cannot convert from ’main::B’ to ’main::A’
const cast
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’

p = q; // error C2440: ’=’ : cannot convert from ’main::B *’ to ’main::A *’

q = p; // error C2440: ’=’ : cannot convert from ’main::A *’ to ’main::B *’

p = (A*)&b; // Forced -- Okay


q = (B*)&a; // Forced -- Okay

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Casting: C-Style:
RECAP (Module 26)
Module 32
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;
Cast
Operators cout << p->i << endl; // prints 5
const cast cout << q->d << endl; // prints 7.2

Summary p = (A*)&b;
q = (B*)&a;

cout << p->i << endl; // prints -858993459 ------------- GARBAGE


cout << q->d << endl; // prints -9.25596e+061 ------------- GARBAGE

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Casting on a Hierarchy: C-Style:
RECAP (Module 26)
Module 32
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

Cast pv = pa; // okay ------------------------------------------------- // Lose the type


Operators pv = pb; // okay ------------------------------------------------- // Lose the type
const cast
pa = pv; // error C2440: ’=’ : cannot convert from ’void *’ to ’A *’
Summary pb = pv; // error C2440: ’=’ : cannot convert from ’void *’ to ’B *’

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Casting on a Hierarchy: C-Style:
RECAP (Module 26)
Module 32
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;
Cast B *pb = &b;
Operators
const cast cout << pa->dataA_ << endl; // prints 2
cout << pb->dataA_ << " " << pb->dataB_ << endl; // prints 3 5
Summary
pa = &b;

cout << pa->dataA_ << endl; // prints 3


// cout << pa->dataB_ << endl; // error C2039: ’dataB_’ : is not a member of ’A’

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Casting in C and C++

Module 32 Casting in C

Partha Pratim Implicit cast


Das Explicit C-Style cast
Loses type information in several contexts
Objectives & Lacks clarity of semantics
Outline

Casting Casting in C++


Upcast &
Downcast Performs fresh inference of types without change of value
Cast
Performs fresh inference of types with change of value
Operators
const cast
Using implicit computation
Using explicit (user-defined) computation
Summary
Preserves type information in all contexts
Provides clear semantics through cast operators:
const cast
static cast
reinterpret cast
dynamic cast
Cast operators can be grep-ed in source
C-Style cast must be avoided in C++
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Cast Operators

Module 32 A cast operator take an expression of source type (implicit


Partha Pratim
Das
from the expression) and convert it to an expression of
target type (explicit in the operator) following the
Objectives &
Outline semantics of the operator
Casting Use of cast operators increases robustness by generating
Upcast &
Downcast errors in static or dynamic time
Cast
Operators
const cast

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Cast Operators

Module 32 const cast operator: const cast<type>(expr)

Partha Pratim Explicitly overrides const and/or volatile in a cast


Das Usually does not perform computation or change value

Objectives & static cast operator: static cast<type>(expr)


Outline
Performs a non-polymorphic cast
Casting Usually performs computation to change value – implicit or
Upcast &
Downcast user-defined
Cast reinterpret cast operator: reinterpret cast<type>(expr)
Operators
const cast Casts between unrelated pointer types or pointer and integer
Summary Does not perform computation yet reinterprets value
dynamic cast operator: dynamic cast<type>(expr)
Performs a run-time cast that verifies the validity of the cast
Performs pre-defined computation, sets null or throws exception

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


const cast Operator

Module 32 const cast converts between types with different


Partha Pratim cv-qualification
Das
Only const cast may be used to cast away (remove)
Objectives &
Outline const-ness or volatility
Casting Usually does not perform computation or change value
Upcast &
Downcast

Cast
Operators
const cast

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


const cast Operator

#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();

// a.set(5); // error: ’void A::set(int)’: cannot convert


// ’this’ pointer from ’const A’ to ’A &’

const_cast<A&>(a).set(5);

// const_cast<A>(a).set(5); // error: ’const_cast’: cannot convert


// from ’const A’ to ’A’
return 0;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


const cast Operator vis-a-vis C-Style Cast

#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

Summary const A a(1);

// const_cast<A&>(a).set(5);
((A&)a).set(5); // C-Style Cast

// const_cast<A>(a).set(5); // error: ’const_cast’: cannot convert


// from ’const A’ to ’A’
((A)a).set(5); // C-Style Cast

return 0;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


const cast Operator
#include <iostream> Output:
Module 32 using namespace std; i = 4
struct type { type() :i(3) {} type::i = 4
Partha Pratim void m1(int v) const { 3 4
Das //this->i = v; // error C3490: ’i’ cannot be modified because
// it is being accessed through a const object
const_cast<type*>(this)->i = v; // OK as long as the type object isn’t const
Objectives &
}
Outline
int i;
Casting };
int main() {
Upcast &
Downcast int i = 3; // i is not declared const
const int& cref_i = i;
Cast const_cast<int&>(cref_i) = 4; // OK: modifies i
Operators cout << "i = " << i << ’\n’;
const cast
type t; // note, if this is const type t;, then t.m1(4); is undefined behavior
Summary t.m1(4);
cout << "type::i = " << t.i << ’\n’;

const int j = 3; // j is declared const


int* pj = const_cast<int*>(&j);
*pj = 4; // undefined behavior! Value of j and *pj may differ
cout << j << " " << *pj << endl;

void (type::*mfp)(int) const = &type::m1; // pointer to member function


//const_cast<void(type::*)(int)>(mfp); // error C2440: ’const_cast’ : cannot convert
// from ’void (__thiscall type::* )(int) const’ to ’void (__thiscall type::* )(int)’
// const_cast does not work on function pointers
return 0;
}
NPTEL MOOCs Programming in C++ Partha Pratim Das 16
Module Summary

Module 32

Partha Pratim Understood casting in C and C++


Das
Explained cast operators in C++ and discussed the evils
Objectives &
Outline of C-style casting
Casting Studied const cast with examples
Upcast &
Downcast

Cast
Operators
const cast

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 18


Module 33

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 33

Partha Pratim Understand casting in C and C++


Das

Objectives &
Outline

Cast
Operators
static cast
reinterpret cast

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 33

Partha Pratim Casting: C-Style: RECAP


Das
Upcast & Downcast
Objectives &
Outline
Cast Operators in C++
Cast
const cast Operator
Operators static cast Operator
static cast
reinterpret cast reinterpret cast Operator
Summary dynamic cast Operator
typeid Operator

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Casting in C and C++

Module 33 Casting in C

Partha Pratim Implicit cast


Das Explicit C-Style cast
Loses type information in several contexts
Objectives & Lacks clarity of semantics
Outline

Cast Casting in C++


Operators
static cast
Performs fresh inference of types without change of value
reinterpret cast Performs fresh inference of types with change of value
Summary Using implicit computation
Using explicit (user-defined) computation
Preserves type information in all contexts
Provides clear semantics through cast operators:
const cast
static cast
reinterpret cast
dynamic cast
Cast operators can be grep-ed in source
C-Style cast must be avoided in C++
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
static cast Operator
static cast performs all conversions allowed implicitly (not only those
Module 33 with pointers to classes), and also the opposite of these. It can:
Partha Pratim Convert from void* to any pointer type
Das
Convert integers, floating-point values and enum types to enum types
Objectives & static cast can perform conversions between pointers to related classes:
Outline

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

Summary Additionally, static cast can also perform the following:


Explicitly call a single-argument constructor or a conversion operator
– The User-Defined Cast
Convert to rvalue references
Convert enum class values into integers or floating-point values
Convert any type to void, evaluating and discarding the value

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


static cast Operator: Built-in Types

#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;

Cast i = d; // implicit -- warning


Operators i = static_cast<int>(d); // static_cast -- okay
static cast i = (int)d; // C-style -- okay
reinterpret cast
d = i; // implicit -- okay
Summary d = static_cast<double>(i); // static_cast -- okay
d = (double)i; // C-style -- okay

i = pd; // implicit -- error


i = static_cast<int>(pd); // static_cast -- error
i = (int)pd; // C-style -- okay: RISKY: Should use reinterpret_cast

return 0;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


static cast Operator: Class Hierarchy

#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;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


static cast Operator: Pitfall

class Window { public: virtual void onResize(); ... }


Module 33
class SpecialWindow: public Window { // derived class
public:
Partha Pratim virtual void onResize() { // derived onResize impl;
Das static_cast<Window>(*this).onResize(); // cast *this to Window,
// then call its onResize;
Objectives & // this doesnt work!
Outline
... // do SpecialWindow-specific stuff
Cast }
Operators ...
static cast };
reinterpret cast

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

... // do SpecialWindow-specific stuff


}
...
};

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


static cast Operator: Unrelated Classes
#include <iostream> #include <iostream>
Module 33 using namespace std; using namespace std;

Partha Pratim // Un-related Types // Un-related Types


Das class B; class B;
class A { class A {
public: public:
Objectives &
A(int i = 0) { cout << "A::A(i)\n"; }
Outline
A(const B&) { cout << "A::A(B&)\n"; }
Cast }; };
Operators
class B { }; class B { };
static cast
reinterpret cast
int main() { int main() {
Summary A a; A a;
B b; B b;
int i = 5; int i = 5;

// 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&)

// int ==> A // int ==> A


a = i; // error a = i; // Uses A::A(int)
a = static_cast<A>(i); // error a = static_cast<A>(i); // Uses A::A(int)
a = (A)i; // error a = (A)i; // Uses A::A(int)

return 0; return 0;
} }

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


static cast Operator: Unrelated Classes
#include <iostream> #include <iostream>
Module 33 using namespace std; using namespace std;

Partha Pratim // Un-related Types // Un-related Types


Das class B; class B;
class A { int i_; public: class A { int i_; public:
A(int i = 0) : i_(i)
Objectives &
{ cout << "A::A(i)\n"; }
Outline
operator int()
Cast { cout << "A::operator int()\n"; return i_; }
Operators }; };
class B { public: class B { public:
static cast
operator A()
reinterpret cast
{ cout << "B::operator A()\n"; return A(); }
Summary }; };
int main() { int main() {
A a; B b; int i = 5; A a; B b; int i = 5;

// 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()

// A ==> int // A ==> int


i = a; // error i = a; // A::operator int()
i = static_cast<int>(a); // error i = static_cast<int>(a); // A::operator int()
i = (int)a; // error i = (int)a; // A::operator int()

return 0; return 0;
} }

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


reinterpret cast Operator
reinterpret cast converts any pointer type to any other pointer type,
Module 33 even of unrelated classes
Partha Pratim The operation result is a simple binary copy of the value from one pointer
Das to the other
Objectives & All pointer conversions are allowed: neither the content pointed nor the
Outline pointer type itself is checked
Cast It can also cast pointers to or from integer types
Operators
static cast
The format in which this integer value represents a pointer is
reinterpret cast platform-specific
Summary The only guarantee is that a pointer cast to an integer type large enough to
fully contain it (such as intptr t), is guaranteed to be able to be cast
back to a valid pointer
The conversions that can be performed by reinterpret cast but not by
static cast are low-level operations based on reinterpreting the binary
representations of the types, which on most cases results in code which is
system-specific, and thus non-portable

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


reinterpret cast Operator

#include <iostream>
Module 33
using namespace std;
Partha Pratim class A {};
Das class B {};

Objectives & int main() {


Outline int i = 2;
double d = 3.7;
Cast double *pd = &d;
Operators
static cast i = pd; // implicit -- error
reinterpret cast i = reinterpret_cast<int>(pd); // reinterpret_cast -- okay
i = (int)pd; // C-style -- okay
Summary cout << pd << " " << i << endl;

A *pA;
B *pB;

pA = pB; // implicit -- error


pA = reinterpret_cast<A*>(pB); // reinterpret_cast -- okay
pA = (A*)pB; // C-style -- okay

return 0;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Module Summary

Module 33

Partha Pratim Studied static cast, and reinterpret cast with


Das
examples
Objectives &
Outline

Cast
Operators
static cast
reinterpret cast

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Module 34

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

Summary Department of Computer Science and Engineering


Indian Institute of Technology, Kharagpur
[email protected]

Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 34

Partha Pratim Understand casting in C and C++


Das

Objectives &
Outline

Cast
Operators
dynamic cast

typeid
Operator

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 34

Partha Pratim Casting: C-Style: RECAP


Das
Upcast & Downcast
Objectives &
Outline
Cast Operators in C++
Cast
const cast Operator
Operators static cast Operator
dynamic cast
reinterpret cast Operator
typeid
Operator dynamic cast Operator
Summary
typeid Operator

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Casting in C and C++

Module 34 Casting in C

Partha Pratim Implicit cast


Das Explicit C-Style cast
Loses type information in several contexts
Objectives & Lacks clarity of semantics
Outline

Cast Casting in C++


Operators
dynamic cast
Performs fresh inference of types without change of value
Performs fresh inference of types with change of value
typeid
Operator Using implicit computation
Summary Using explicit (user-defined) computation
Preserves type information in all contexts
Provides clear semantics through cast operators:
const cast
static cast
reinterpret cast
dynamic cast
Cast operators can be grep-ed in source
C-Style cast must be avoided in C++
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
dynamic cast Operator

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


dynamic cast Operator: Pointers
#include <iostream> Output:
Module 34 using namespace std; 00EFFCA8 casts to 00EFFCA8: Up-cast: Valid
00EFFCA8 casts to 00EFFCA8: Down-cast: Valid
Partha Pratim class A { public: virtual ~A() {} }; 00EFFCB4 casts to 00000000: Down-cast: Invalid
Das class B: public A { }; 00EFFC9C casts to 00000000: Unrelated-cast: Invalid
class C { public: virtual ~C() {} }; 00000000 casts to 00000000: Unrelated: Valid for null
int main() { 00EFFCB4 casts to 00EFFCB4: Cast-to-void: Valid
Objectives &
A a; B b; C c; A *pA; B *pB; C *pC; void *pV;
Outline

Cast pB = &b; pA = dynamic_cast<A*>(pB);


Operators cout << pB << " casts to " << pA << ": Up-cast: Valid" << endl;
dynamic cast
pA = &b; pB = dynamic_cast<B*>(pA);
typeid cout << pA << " casts to " << pB << ": Down-cast: Valid" << endl;
Operator
pA = &a; pB = dynamic_cast<B*>(pA);
Summary cout << pA << " casts to " << pB << ": Down-cast: Invalid" << endl;

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;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


typeid Operator

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Using typeid Operator:
Polymorphic Hierarchy
Module 34 #include <iostream>
#include <typeinfo>
using namespace std;
Partha Pratim
Das
// Polymorphic Hierarchy
class A { public: virtual ~A() {} };
Objectives & class B : public A {};
Outline
int main() {
Cast A a;
Operators cout << typeid(a).name() << ": " << typeid(&a).name() << endl; // Static
dynamic cast A *p = &a;
cout << typeid(p).name() << ": " << typeid(*p).name() << endl; // Dynamic
typeid
Operator B b;
Summary cout << typeid(b).name() << ": " << typeid(&b).name() << endl; // Static
p = &b;
cout << typeid(p).name() << ": " << typeid(*p).name() << endl; // Dynamic

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;
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Module Summary

Module 34

Partha Pratim Understood casting at run-time


Das
Studied dynamic cast with examples
Objectives &
Outline Understood RTTI and typeid operator
Cast
Operators
dynamic cast

typeid
Operator

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Module 35

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 35

Partha Pratim Understand Multiple Inheritance in C++


Das

Objectives &
Outline

Multiple
Inheritance in
C++
Semantics
Data Members
Overrides and
Overloads
protected
Access
Constructor &
Destructor
Object Lifetime

Diamond
Problem
Exercise

Design Choice

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 35

Partha Pratim Multiple Inheritance in C++


Das
Semantics
Objectives & Data Members and Object Layout
Outline
Member Functions
Multiple
Inheritance in
protected Access
C++ Constructor & Destructor
Semantics
Data Members Object Lifetime
Overrides and
Overloads
protected
Diamond Problem
Access
Constructor & Exercise
Destructor
Object Lifetime
Design Choice
Diamond
Problem
Exercise

Design Choice

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


Multiple Inheritance in C++: Hierarchy

TA ISA Student; TA ISA Faculty


Module 35

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Multiple Inheritance in C++: Hierarchy

Manager ISA Employee, Director ISA Employee, ManagingDirector ISA


Module 35
Manager, ManagingDirector ISA Director
Partha Pratim
Das

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

Module 35 Derived ISA Base1, Derived ISA Base2


Partha Pratim
Das

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Multiple Inheritance in C++: Semantics

Derived ISA Base1, Base2


Module 35
Data Members
Partha Pratim
Das Derived class inherits all data members of all Base classes
Derived class may add data members of its own
Objectives &
Outline Member Functions
Multiple Derived class inherits all member functions of all Base classes
Inheritance in
C++ Derived class may override a member function of any Base class by
Semantics redefining it with the same signature
Data Members Derived class may overload a member function of any Base class by
Overrides and
Overloads redefining it with the same name; but different signature
protected
Access Access Specification
Constructor &
Destructor
Object Lifetime Derived class cannot access private members of any Base class
Diamond
Derived class can access protected members of any Base class
Problem
Construction-Destruction
Exercise

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Multiple Inheritance in C++:
Data Members and Object Layout
class Base1 { protected:
Module 35 int i_;
int data_;
Partha Pratim public: // ...
Das };
class Base2 { protected:
int j_;
Objectives &
int data_;
Outline
public: // ...
Multiple };
Inheritance in class Derived : public Base1, public Base2 {
C++ int k_;
Semantics
public: // ...
Data Members };
Overrides and
Overloads Object Layout
protected
Access Object Base1 Object Base2 Object Derived
Constructor &
Destructor
Object Lifetime i
data
Diamond
Problem i j
Exercise data data
j
Design Choice data

Summary k

Object Derived has two data member!


Ambiguity to be resolved with base class name: Base1::data & Base2::data
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Multiple Inheritance in C++:
Member Functions – Overrides and Overloads
Module 35 Derived ISA Base1, Base2
Partha Pratim
Das
Member Functions
Derived class inherits all member functions of all Base
Objectives &
Outline classes
Multiple Derived class may override a member function of any Base
Inheritance in
C++
class by redefining it with the same signature
Semantics Derived class may overload a member function of any Base
Data Members
Overrides and class by redefining it with the same name; but different
Overloads
protected signature
Access
Constructor &
Destructor
Object Lifetime
Static Member Functions
Diamond Derived class does not inherit the static member functions
Problem
Exercise
of any Base class
Design Choice
Friend Functions
Summary
Derived class does not inherit the friend functions of any
Base class
NPTEL MOOCs Programming in C++ Partha Pratim Das 10
Multiple Inheritance in C++:
Member Functions – Overrides and Overloads
Module 35 class Base1 { protected:
int i_;
Partha Pratim int data_;
Das public: Base1(int a, int b) : i_(a), data_(b);
void f(int) { cout << "Base1::f(int) "; }
void g() { cout << "Base1::g() "; }
Objectives & };
Outline class Base2 { protected:
int j_;
Multiple
int data_;
Inheritance in
public: Base2(int a, int b) : j_(a), data_(b);
C++
void h(int) { cout << "Base2::h(int) "; }
Semantics };
Data Members
class Derived : public Base1, public Base2 {
Overrides and
Overloads int k_;
protected public: Derived(int x, int y, int u, int v, int z);
Access void f(int) { cout << "Derived::f(int) "; } // -- Overridden Base1::f(int)
Constructor & // -- Inherited Base1::g()
Destructor
void h(string) { cout << "Derived::h(string) "; } // -- Overloaded Base2:: h(int)
Object Lifetime
void e(char) { cout << "Derived::e(char) "; } // -- Added Derived::e(char)
Diamond };
Problem
Exercise Derived c(1, 2, 3, 4, 5);

Design Choice c.f(5); // Derived::f(int) -- Overridden Base1::f(int)


c.g(); // Base1::g() -- Inherited Base1::g()
Summary c.h("ppd"); // Derived::h(string) -- Overloaded Base2:: h(int)
c.e(’a’); // Derived::e(char) -- Added Derived::e(char)

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Inheritance in C++:
Member Functions – using for Name Resolution
Ambiguous Calls Unambiguous Calls
Module 35
class Base1 { public: class Base1 { public:
Partha Pratim Base1(int a, int b) : i_(a), data_(b); Base1(int a, int b) : i_(a), data_(b);
Das void f(int) { cout << "Base1::f(int) "; } void f(int) { cout << "Base1::f(int) "; }
void g() { cout << "Base1::g() "; } void g() { cout << "Base1::g() "; }
}; };
Objectives &
class Base2 { public: class Base2 { public:
Outline
Base2(int a, int b) : j_(a), data_(b); Base2(int a, int b) : j_(a), data_(b);
Multiple void f(int) { cout << "Base2::f(int) "; } void f(int) { cout << "Base2::f(int) "; }
Inheritance in void g(int) { cout << "Base2::g(int) "; } void g(int) { cout << "Base2::g(int) "; }
C++ }; };
Semantics
class Derived : public Base1, public Base2 { class Derived : public Base1, public Base2 {
Data Members public: Derived(int x, int y, int u, public: Derived(int x, int y, int u,
Overrides and int v, int z); int v, int z);
Overloads using Base1::f; // Hides Base2::f
protected using Base2::g; // Hides Base1::g
Access }; };
Constructor &
Destructor
Object Lifetime Derived c(1, 2, 3, 4, 5); Derived c(1, 2, 3, 4, 5);

Diamond c.f(5); // Base1::f(int) or Base2::f(int)? c.f(5); // Base1::f(int)


Problem c.g(5); // Base1::g() or Base2::g(int)? c.g(5); // Base2::g(int)
Exercise c.f(3); // Base1::f(int) or Base2::f(int)? c.Base2::f(3); // Base2::f(int)
c.g(); // Base1::g() or Base2::g(int)? c.Base1::g(); // Base1::g()
Design Choice
• Overload resolution does not work between Base1::g(int) and Base2::g()
Summary
• using hides other candidates
• Explicit use of base class name can resolve (weak solution)

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Multiple Inheritance in C++:
Access Members of Base: protected Access
Module 35 Access Specification
Partha Pratim
Das
Derived class cannot access private members of any Base
class
Objectives & Derived class can access protected members of any Base
Outline
class
Multiple
Inheritance in
C++
Semantics
Data Members
Overrides and
Overloads
protected
Access
Constructor &
Destructor
Object Lifetime

Diamond
Problem
Exercise

Design Choice

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Multiple Inheritance in C++:
Constructor & Destructor
Module 35 Constructor-Destructor
Partha Pratim
Das
Derived class inherits all Constructors and Destructor of
Base classes (but in a different semantics)
Objectives & Derived class cannot override or overload a Constructor or
Outline
the Destructor of any Base class
Multiple
Inheritance in
C++ Construction-Destruction
Semantics
Data Members A constructor of the Derived class must first call all
Overrides and
Overloads constructors of the Base classes to construct the Base
protected
Access class instances of the Derived class
Constructor &
Destructor
Object Lifetime
Base class constructors are called in listing order
Diamond
The destructor of the Derived class must call the
Problem destructors of the Base classes to destruct the Base class
Exercise
instances of the Derived class
Design Choice

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Multiple Inheritance in C++:
Constructor & Destructor
class Base1 { protected: int i_; int data_;
Module 35 public: Base1(int a, int b) : i_(a), data_(b) { cout << "Base1::Base1() "; }
~Base1() { cout << "Base1::~Base1() "; }
Partha Pratim };
Das class Base2 { protected: int j_; int data_;
public: Base2(int a = 0, int b = 0) : j_(a), data_(b) { cout << "Base2::Base2() "; }
~Base2() { cout << "Base2::~Base2() "; }
Objectives &
};
Outline
class Derived : public Base1, public Base2 { int k_;
Multiple public: Derived(int x, int y, int z) :
Inheritance in Base1(x, y), k_(z) { cout << "Derived::Derived() "; }
C++ // Base1::Base1 explicit, Base2::Base2 default
Semantics
~Derived() { cout << "Derived::~Derived() "; }
Data Members };
Overrides and Base1 b1(2, 3);
Overloads Base2 b2(3, 7);
protected Derived d(5, 3, 2);
Access
Constructor & Object Layout
Destructor
Object Lifetime
Object b1 Object b2 Object d
Diamond
Problem 5
Exercise 3
Design Choice 2 3
3 7
Summary 0
0

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 16


Multiple Inheritance in C++: Diamond Problem

Student ISA Person


Module 35
Faculty ISA Person
Partha Pratim
Das TA ISA Student; TA ISA Faculty

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Multiple Inheritance in C++:
Diamond Problem
Module 35 #include<iostream>
using namespace std;
Partha Pratim
Das class Person { // Data members of person
public: Person(int x) { cout << "Person::Person(int)" << endl; }
};
Objectives & class Faculty : public Person { // data members of Faculty
Outline public: Faculty(int x) :Person(x) { cout << "Faculty::Faculty(int)" << endl; }
};
Multiple
class Student : public Person { // data members of Student
Inheritance in
public: Student(int x) :Person(x) { cout << "Student::Student(int)" << endl; }
C++
};
Semantics class TA : public Faculty, public Student {
Data Members
public: TA(int x) :Student(x), Faculty(x) { cout << "TA::TA(int)" << endl; }
Overrides and
Overloads };
protected int main() {
Access TA ta(30);
Constructor &
Destructor
return 0;
Object Lifetime
}
Diamond -----
Problem Person::Person(int)
Exercise Faculty::Faculty(int)
Person::Person(int)
Design Choice Student::Student(int)
TA::TA(int)
Summary
• Two instances of base class object (Person) in a TA object!

NPTEL MOOCs Programming in C++ Partha Pratim Das 18


Multiple Inheritance in C++:
virtual Inheritance – virtual Base Class
#include<iostream>
Module 35
using namespace std;
Partha Pratim class Person { // Data members of person
Das public: Person(int x) { cout << "Person::Person(int)" << endl; }
Person() { cout << "Person::Person()" << endl; } // Default ctor for virtual inheritance
Objectives & };
Outline class Faculty : virtual public Person { // data members of Faculty
public: Faculty(int x) :Person(x) { cout << "Faculty::Faculty(int)" << endl; }
Multiple };
Inheritance in class Student : virtual public Person { // data members of Student
C++ public: Student(int x) :Person(x) { cout << "Student::Student(int)" << endl; }
Semantics };
Data Members class TA : public Faculty, public Student {
Overrides and public: TA(int x) :Student(x), Faculty(x) { cout << "TA::TA(int)" << endl; }
Overloads };
protected int main() {
Access
Constructor & TA ta(30);
Destructor
Object Lifetime return 0;
}
Diamond -----
Problem Person::Person()
Exercise Faculty::Faculty(int)
Design Choice Student::Student(int)
TA::TA(int)
Summary • Introduce a default constructor for root base class Person
• Prefix every inheritance of Person with virtual
• Only one instance of base class object (Person) in a TA object!

NPTEL MOOCs Programming in C++ Partha Pratim Das 19


Multiple Inheritance in C++:
virtual Inheritance with Parameterized Ctor
#include<iostream>
Module 35
using namespace std;
class Person {
Partha Pratim public: Person(int x) { cout << "Person::Person(int)" << endl; }
Das Person() { cout << "Person::Person()" << endl; }
};
Objectives & class Faculty : virtual public Person {
Outline public: Faculty(int x) :Person(x) { cout << "Faculty::Faculty(int)" << endl; }
};
Multiple class Student : virtual public Person {
Inheritance in public: Student(int x) :Person(x) { cout << "Student::Student(int)" << endl; }
C++ };
Semantics class TA : public Faculty, public Student {
Data Members public:
Overrides and TA(int x):Student(x), Faculty(x), Person(x) { cout << "TA::TA(int)" << endl; }
Overloads };
protected int main() {
Access
Constructor & TA ta(30);
Destructor
Object Lifetime return 0;
}
Diamond -----
Problem Person::Person(int)
Exercise Faculty::Faculty(int)
Design Choice Student::Student(int)
TA::TA(int )
Summary
• Call parameterized constructor of root base class Person from constructor of TA class

NPTEL MOOCs Programming in C++ Partha Pratim Das 20


Multiple Inheritance in C++:
Ambiguity
#include<iostream>
Module 35
using namespace std;
class Person {
Partha Pratim public: Person(int x) { cout << "Person::Person(int)" << endl; }
Das Person() { cout << "Person::Person()" << endl; }
virtual ~Person();
Objectives & virtual void teach() = 0;
Outline };
class Faculty : virtual public Person {
Multiple public: Faculty(int x) :Person(x) { cout << "Faculty::Faculty(int)" << endl; }
Inheritance in virtual void teach();
C++ };
Semantics class Student : virtual public Person {
Data Members public: Student(int x) :Person(x) { cout << "Student::Student(int)" << endl; }
Overrides and virtual void teach();
Overloads };
protected class TA : public Faculty, public Student {
Access
Constructor & public:
Destructor TA(int x):Student(x), Faculty(x) { cout << "TA::TA(int)" << endl; }
Object Lifetime virtual void teach();
};
Diamond
Problem • In the absence of TA::teach(), which of Student::teach() or Faculty::teach() should be inherited?
Exercise

Design Choice

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 21


Multiple Inheritance in C++:
Exercise
class A {
Module 35
public:
virtual ~A() { cout << "A::~A()" << endl; }
Partha Pratim virtual void foo() { cout << "A::foo()" << endl; }
Das };
class B : public virtual A {
Objectives & public:
Outline virtual ~B() { cout << "B::~B()" << endl; }
virtual void foo() { cout << "B::foo()" << endl; }
Multiple };
Inheritance in class C { // : public virtual A {
C++ public:
Semantics virtual ~C() { cout << "C::~C()" << endl; }
Data Members virtual void foobar() { cout << "C::foobar()" << endl; }
Overrides and };
Overloads
protected class D : public B, public C {
Access
Constructor & public:
Destructor virtual ~D() { cout << "D::~D()" << endl; }
Object Lifetime virtual void foo() { cout << "D::foo()" << endl; }
virtual void foobar() { cout << "D::foobar()" << endl; }
Diamond };
Problem
Exercise • Consider the effect of calling foo and foobar for various objects and various pointers
Design Choice

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 22


Design Choice:
Inheritance or Composition
Module 35 Vehicle Hierarchy
Partha Pratim
Das

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 23


Design Choice:
Inheritance or Composition
Module 35 Vehicle Hierarchy
Partha Pratim
Das

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 24


Design Choice:
Inheritance or Composition
Module 35 Vehicle Hierarchy
Partha Pratim
Das

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 25


Module Summary

Module 35

Partha Pratim Introduced the Semantics of Multiple Inheritance in C++


Das
Discussed the Diamond Problem and solution approaches
Objectives &
Outline Illustrated the design choice between inheritance and
Multiple
Inheritance in
composition
C++
Semantics
Data Members
Overrides and
Overloads
protected
Access
Constructor &
Destructor
Object Lifetime

Diamond
Problem
Exercise

Design Choice

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 26


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 27


Module 36

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

Partha Pratim Understand the Error handling in C


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

Partha Pratim Conditions that arise


Das
Infrequently and Unexpectedly
Objective & Generally betray a Program Error
Outline
Require a considered Programmatic Response
Exception
Fundamentals
Run-time Anomalies – yes, but not necessarily
Types of
Exceptions Leading to
Exception Stages
Crippling the Program
Exceptions in
C May pull the entire System down
C Language
Features
Defensive Technique
RV & Params
Local goto
Crashing Exceptions verses Tangled Design and Code
C Standard
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 4
Exception Causes

Module 36 Unexpected Systems State


Partha Pratim Exhaustion of Resources
Das
Low Free Store Memory
Objective & Low Disk Space
Outline
Pushing to a Full Stack
Exception
Fundamentals External Events
Types of
Exceptions
Exception Stages

Exceptions in
Socket Event
C Logical Errors
C Language
Features Pop from an Empty Stack
RV & Params
Local goto Resource Errors – like Memory Read/Write
C Standard
Library Support
Global Variables
Run time Errors
Abnormal
Termination Arithmetic Overflow / Underflow
Conditional
Termination Out of Range
Non-Local goto
Signals
Shortcomings
Undefined Operation
Summary Division by Zero
NPTEL MOOCs Programming in C++ Partha Pratim Das 5
Exception Handling?

Module 36

Partha Pratim Exception Handling is a mechanism that separates the


Das
detection and handling of circumstantial Exceptional Flow
Objective &
Outline
from Normal Flow
Exception Current state saved in a pre-defined location
Fundamentals
Types of
Exceptions
Execution switched to a pre-defined handler
Exception Stages

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

Partha Pratim Asynchronous Exceptions:


Das
Exceptions that come Unexpectedly
Objective & Example - an Interrupt in a Program
Outline
Takes control away from the Executing Thread context to
Exception
Fundamentals
a context that is different from that which caused the
Types of
Exceptions
exception
Exception Stages
Synchronous Exceptions:
Exceptions in
C Planned Exceptions
C Language
Features Handled in an organized manner
RV & Params
Local goto
The most common type of Synchronous Exception is
C Standard
Library Support
implemented as a throw
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Exception Stages

Module 36 1 Error Incidence


Partha Pratim Synchronous (S/W) Logical Error
Das
Asynchronous (H/W) Interrupt (S/W Interrupt)
Objective & 2 Create Object & Raise Exception
Outline
An Exception Object can be of any Complete Type
Exception
Fundamentals An int to a full blown C++ class object
Types of
Exceptions 3 Detect Exception
Exception Stages
Polling Software Tests
Exceptions in
C Notification Control (Stack) Adjustments
C Language
Features 4 Handle Exception
RV & Params
Local goto Ignore: hope someone else handles it, that is, Do Not Catch
C Standard
Library Support Act: but allow others to handle it afterwards, that is, Catch, Handle
Global Variables and Re-Throw
Abnormal
Termination Own: take complete ownership, that is, Catch and Handle
Conditional
Termination 5 Recover from Exception
Non-Local goto
Signals
Shortcomings
Continue Execution: If handled inside the program
Abort Execution: If handled outside the program
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 8
Exception Stages

Module 36

Partha Pratim int f() {


Das
int error;
/* ... */
Objective &
Outline if (error) /* Stage 1: error occurred */
return -1; /* Stage 2: generate exception object */
Exception
Fundamentals /* ... */
Types of }
Exceptions
Exception Stages
int main(void) {
Exceptions in
C if (f() != 0) /* Stage 3: detect exception */
C Language {
Features
RV & Params
/* Stage 4: handle exception */
Local goto }
C Standard /* Stage 5: recover */
Library Support
Global Variables }
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 9
Support for Exceptions in C

Module 36

Partha Pratim Language Features


Das
Return Value & Parameters
Objective & Local goto
Outline
Standard Library Support
Exception
Fundamentals Global Variables
Types of
Exceptions Abnormal Termination
Exception Stages
Conditional Termination
Exceptions in
C Non-Local goto
C Language
Features Signals
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 10
Return Value & Parameters

Module 36

Partha Pratim Function Return Value Mechanism


Das
Created by the Callee as Temporary Objects
Objective & Passed onto the Caller
Outline
Caller checks for Error Conditions
Exception
Fundamentals
Return Values can be ignored and lost
Types of
Exceptions
Return Values are temporary
Exception Stages
Function (output) Parameter Mechanism
Exceptions in
C Outbound Parameters, bound to arguments, offer multiple
C Language
Features logical Return Values
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 11
Example: Return Value & Parameters

Module 36

Partha Pratim int Push(int i) {


Das
if (top_ == size-1) // Incidence
return 0; // Raise
Objective &
Outline else
stack_[++top_] = i;
Exception
Fundamentals
Types of return 1;
Exceptions
Exception Stages
}
Exceptions in
C int main() {
C Language int x;
Features
RV & Params
// ...
Local goto if (!Push(x)) // Detect {
C Standard // Handling
Library Support
Global Variables }
Abnormal
Termination // Recovery
Conditional }
Termination
Non-Local goto
Signals
Shortcomings

Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 12
Local goto

Module 36

Partha Pratim Local goto Mechanism


Das
(At Source) Escapes: Gets Control out of a Deep Nested
Objective & Loop
Outline
(At Destination) Refactors: Actions from Multiple Points
Exception
Fundamentals
of Error Inception
Types of
Exceptions A group of C Features
Exception Stages
goto Label;
Exceptions in
C break; & continue;
C Language
Features default switch case
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 13
Example: Local goto

Module 36

Partha Pratim _PHNDLR _cdecl signal(int signum, _PHNDLR sigact)


Das
{ // Lifted from VC98\CRT\SRC\WINSIG.C
... /* Check for sigact support */
Objective &
Outline if ( (sigact == ...) ) goto sigreterror;
Exception
Fundamentals /* Not exceptions in the host OS. */
Types of if ( (signum == ... ) { ... goto sigreterror; }
Exceptions
Exception Stages
else { ... goto sigretok; }
Exceptions in
C /* Exceptions in the host OS. */
C Language if ( (signum ...) ) goto sigreterror;
Features
RV & Params
...
Local goto sigretok:
C Standard return(oldsigact);
Library Support
Global Variables
Abnormal
Termination sigreterror:
Conditional errno = EINVAL;
Termination
Non-Local goto return(SIG_ERR);
Signals }
Shortcomings

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

Partha Pratim GV Mechanism


Das
Use a designated Global Error Variable
Objective & Set it on Error
Outline
Poll / Check it for Detection
Exception
Fundamentals Standard Library GV Mechanism
Types of
Exceptions <errno.h > / <cerrno>
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 18
Example: Global Variables

Module 36 #include <errno.h>


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

Objective & int main() {


Outline double x, y, result;
Exception /*... somehow set ’x’ and ’y’ ...*/
Fundamentals errno = 0;
Types of
Exceptions
Exception Stages result = pow (x, y);
Exceptions in
C if (errno == EDOM)
C Language printf("Domain error on x/y pair \n");
Features
RV & Params
Local goto else if (errno == ERANGE)
C Standard
Library Support printf("range error in result \n");
Global Variables
Abnormal
Termination else
Conditional
Termination printf("x to the y = %d \n", (int) result);
Non-Local goto
Signals
Shortcomings return 0;
}
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 19
Abnormal Termination

Module 36

Partha Pratim Program Halting Functions provided by


Das
<stdlib.h> / <cstdlib>
Objective &
Outline
abort()
Exception
Fundamentals Catastrophic Program Failure
Types of
Exceptions
Exception Stages exit()
Exceptions in
C Code Clean up via atexit() Registrations
C Language
Features
RV & Params
atexit()
Local goto
C Standard
Library Support
Handlers called in reverse order of their Registrations
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

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

Exception static void atexit_handler_2(void) {


Fundamentals printf("within ’atexit_handler_2’ \n");
Types of
Exceptions
}
Exception Stages

Exceptions in int main(){


C atexit(atexit_handler_1);
C Language
Features
atexit(atexit_handler_2);
RV & Params exit(EXIT_SUCCESS);
Local goto
C Standard
Library Support printf("This line should never appear \n");
Global Variables
Abnormal
Termination return 0;
Conditional
Termination }
Non-Local goto /* On Execution Output: within ’atexit_handler_2’
Signals
Shortcomings
within ’atexit_handler_1’
and returns a success code to calling environment */
Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 21
Conditional Termination

Module 36

Partha Pratim Diagnostic ASSERT macro defined in


Das
<assert.h> / <cassert>
Objective &
Outline
Assertions valid when NDEBUG macro is not defined (debug
Exception build is done)
Fundamentals
Types of Assert calls internal function, reports the source file details
Exceptions
Exception Stages and then Terminates
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 22
Example: Conditional Termination

Module 36 /* Debug version */


//#define NDEBUG
Partha Pratim #include <cassert>
Das #include <cstdlib>
#include <cstdio>
using namespace std;
Objective &
Outline int main() {
int i = 0;
Exception
assert(++i == 0); // Assert 0 here
Fundamentals
Types of printf(" i is %d \n", i);
Exceptions
Exception Stages
return 0;
Exceptions in }
C /* When run - Asserts */
C Language
Features void _assert(int test, char const * test_image,
RV & Params char const * file, int line) {
Local goto
C Standard if (!test){
Library Support
Global Variables printf("assertion failed: %s , file %s , line %d\n",
Abnormal test_image, file, line);
Termination abort();
Conditional }
Termination }
Non-Local goto
Signals
Shortcomings

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

Module 36 /* Release version */


#define NDEBUG
Partha Pratim #include <cassert>
Das #include <cstdlib>
#include <cstdio>
using namespace std;
Objective &
Outline int main(){
int i = 0;
Exception
assert(++i == 0); // Assert 0 here
Fundamentals
Types of printf(" i is %d \n", i);
Exceptions
Exception Stages
return 0;
Exceptions in }
C /* When run yields ’i’ is 0 */
C Language
Features void _assert(int test, char const * test_image,
RV & Params char const * file, int line) {
Local goto
C Standard if (!test){
Library Support
Global Variables printf("assertion failed: %s , file %s , line %d\n",
Abnormal test_image, file, line);
Termination abort();
Conditional }
Termination }
Non-Local goto
Signals
Shortcomings

Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 25
Non-Local goto

Module 36

Partha Pratim setjmp() and longjmp() functions provided in


Das
<setjmp.h> Header along with collateral type jmp buf
Objective &
Outline
setjmp(jmp buf)
Exception Sets the Jump point filling up the jmp buf object with the
Fundamentals current program context
Types of
Exceptions
Exception Stages longjmp(jmp buf, int)
Exceptions in Effects a Jump to the context of the jmp buf object
C
C Language Control return to setjmp call last called on jmp buf
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 26
Example: Non-Local goto: The Dynamics

Module 36 Caller Callee


Partha Pratim
Das jmp_buf jbuf ;
void f() {
A a;
Objective & void g(){
Outline if (setjmp(jbuf) == 0)
A a;
{
Exception UsrExcp ex ("From g()");
Fundamentals
B b;
Types of g();
Exceptions longjmp(jbuf, 1);
Exception Stages
h();
}
Exceptions in return ;
C
else {
}
C Language cout << ex.what();
Features
RV & Params
}
Local goto return ;
C Standard }
Library Support
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

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

Partha Pratim Header <signal.h>


Das
raise()
Objective &
Outline
Sends a signal to the executing program
Exception signal()
Fundamentals
Types of Registers interrupt signal handler
Exceptions
Exception Stages Returns the previous handler associated with the given
Exceptions in signal
C
C Language
Features
Converts h/w interrupts to s/w interrupts
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 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

Partha Pratim Destructor-ignorant:


Das
Cannot release Local Objects i.e. Resources Leak
Objective &
Outline
Obtrusive:
Exception
Fundamentals Interrogating RV or GV results in Code Clutter
Types of
Exceptions
Exception Stages Inflexible:
Exceptions in
C Spoils Normal Function Semantics
C Language
Features
RV & Params
Non-native:
Local goto
C Standard
Library Support
Require Library Support outside Core Language
Global Variables
Abnormal
Termination
Conditional
Termination
Non-Local goto
Signals
Shortcomings

Summary
NPTEL MOOCs Programming in C++ Partha Pratim Das 34
Module Summary

Module 36

Partha Pratim Introduced the concept of exceptions


Das
Discussed exception (error) handling in C
Objective &
Outline Illustrated various language features and library support in
Exception
Fundamentals
C for handling errors
Types of
Exceptions Demonstrated with examples
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 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 37

Partha Pratim Understand the Error handling in C++


Das

Objective &
Outline

Exceptions in
C++
Exception Scope
(try)
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline
Exception Fundamentals
Module 37
Types of Exceptions
Partha Pratim Exception Stages
Das
Exceptions in C
Objective & C Language Features
Outline

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

Partha Pratim Separate Error-Handling code from Ordinary code


Das
Language Mechanism rather than of the Library
Objective &
Outline Compiler for Tracking Automatic Variables
Exceptions in
C++ Schemes for Destruction of Dynamic Memory
Exception Scope
(try)
Exception
Less Overhead for the Designer
Arguments
(catch)
Exception
Exception Propagation from the deepest of levels
Matching
Exception Raise
(throw)
Various Exceptions handled by a single Handler
Advantages

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


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

g() called

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


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

g() successfully returns

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


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

g() called and exception raised


Exception caught by catch clause
NPTEL MOOCs Programming in C++ Partha Pratim Das 7
Exception Flow

Module 37 #include <iostream> void f() { MyClass a;


#include <exception> try {
Partha Pratim using namespace std; g();
Das }
class MyException : public exception {}; catch (MyException) { cout << "MyException";
class MyClass {}; catch (exception) { cout << "exception"; }
Objective & catch (...) { throw; }
Outline void h() { MyClass a; }
Exceptions in
//throw 1; int main() {
C++
try {
Exception Scope //throw 2.5;
(try) f();
Exception }
Arguments //throw MyException(); catch (...) { cout << "Unknown"; }
(catch)
Exception //throw exception(); return 0;
Matching
Exception Raise }
(throw) //throw MyClass();
Advantages }
Summary void g() { MyClass a;
try {
h();
}
catch (int) { cout << "int"; }
catch (double) { cout << "double"; }
catch (...) { throw; }
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


try Block: Exception Scope

Module 37 try block


Partha Pratim
Das
Consolidate areas that might throw exceptions

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


catch Block: Exception Arguments

Module 37 catch block


Partha Pratim
Das
Name for the Exception Handler
Catching an Exception is like invoking a function
Objective & Immediately follows the try block
Outline
Unique Formal Parameter for each Handler
Exceptions in
C++ Can be simply a Type Name to distinguish its Handler
Exception Scope
(try) from others
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


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

catch Block

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


try-catch: Exception Matching

Module 37 Exact Match


Partha Pratim
Das
The catch argument type matches the type of the thrown
object
Objective &
Outline No implicit conversion is allowed
Exceptions in
C++ Generalization / Specialization
Exception Scope
(try) The catch argument is a public base class of the thrown
Exception
Arguments
(catch)
class object
Exception
Matching
Exception Raise
Pointer
(throw)
Advantages Pointer types – convertible by standard conversion
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


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

Expression Matching

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


try-catch: Exception Matching

Module 37 In the order of appearance with matching


Partha Pratim
Das
If Base Class catch block precedes Derived Class catch
block
Objective &
Outline Compiler issues a warning and continues
Exceptions in Unreachable code (derived class handler) ignored
C++
Exception Scope
(try) catch(...) block must be the last catch block because
Exception
Arguments
(catch)
it catches all exceptions
Exception
Matching If no matching Handler is found in the current scope, the
Exception Raise
(throw)
Advantages
search continues to find a matching handler in a
Summary dynamically surrounding try block
Stack Unwinds
If eventually no handler is found, terminate() is called

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


throw Expression: Exception Raise

Module 37 Expression is treated the same way as


Partha Pratim
Das
A function argument in a call or the operand of a return
statement
Objective &
Outline Exception Context
Exceptions in
C++ class Exception ;
Exception Scope
(try)
Exception
The Expression
Arguments
(catch)
Exception Generate an Exception object to throw
Matching
Exception Raise
(throw)
throw Exception();
Advantages

Summary
Or, Copies an existing Exception object to throw
Exception ex;
...
throw ex; // Exception(ex);

Exception object is created on the Free Store


NPTEL MOOCs Programming in C++ Partha Pratim Das 16
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

throw Expression

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


throw Expression: Restrictions

Module 37 For a UDT Expression


Partha Pratim
Das
Copy Constructor and Destructor should be supported

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 18


(re)-throw: Throwing Again?

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 19


Advantages

Module 37

Partha Pratim Destructor-savvy:


Das
Stack unwinds; Orderly destruction of Local-objects
Objective &
Outline
Unobtrusive:
Exceptions in
C++ Exception Handling is implicit and automatic
Exception Scope
(try) No clutter of error checks
Exception
Arguments
(catch)
Exception
Precise:
Matching
Exception Raise
(throw)
Exception Object Type designed using semantics
Advantages

Summary
Native and Standard:
EH is part of the C++ language
EH is available in all standard C++ compilers

NPTEL MOOCs Programming in C++ Partha Pratim Das 20


Advantages

Module 37

Partha Pratim Scalable:


Das
Each function can have multiple try blocks
Objective &
Outline
Each try block can have a single Handler or a group of
Exceptions in
Handlers
C++ Each Handler can catch a single type, a group of types, or
Exception Scope
(try) all types
Exception
Arguments
(catch)
Exception
Fault-tolerant:
Matching
Exception Raise
(throw)
Functions can specify the exception types to throw;
Advantages Handlers can specify the exception types to catch
Summary Violation behavior of these specifications is predictable and
user-configurable

NPTEL MOOCs Programming in C++ Partha Pratim Das 21


Module Summary

Module 37

Partha Pratim Discussed exception (error) handling in C++


Das
Illustrated try-throw-catch feature in C++ for handling
Objective &
Outline errors
Exceptions in
C++
Demonstrated with examples
Exception Scope
(try)
Exception
Arguments
(catch)
Exception
Matching
Exception Raise
(throw)
Advantages

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 22


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 23


Module 38

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 38

Partha Pratim Understand Templates in C++


Das

Objectives &
Outline

What is a
Template?

Function
Template
Definition
Instantiation
Template
Argument
Deduction
Example

typename

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 38

Partha Pratim What is a Template?


Das
Function Template
Objectives &
Outline
Function Template Definition
What is a
Instantiation
Template? Template Argument Deduction
Function Example
Template
Definition
Instantiation
typename
Template
Argument Class Template
Deduction
Example Class Template Definition
typename Instantiation
Summary Partial Template Instantiation & Default Template
Parameters
Inheritance

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


What is a Template?

Module 38

Partha Pratim Templates are specifications of a collection of functions or


Das
classes which are parameterized by types
Objectives &
Outline Examples:
What is a Function search, min etc.
Template?
The basic algorithms in these functions are the same
Function
Template independent of types
Definition Yet, we need to write different versions of these functions
Instantiation
Template for strong type checking in C++
Argument
Deduction
Example
Classes list, queue etc.
typename The data members and the methods are almost the same
Summary
for list of numbers, list of objects
Yet, we need to define different classes

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Function Template:
Code reuse in Algorithms
Module 38
We need to compute the maximum of two values that can be of:
Partha Pratim int
Das
double
char * (C-String)
Objectives &
Outline Complex (user-defined class for complex numbers)
What is a
...
Template? We can do this with overloaded Max functions:
Function
Template int Max(int x, int y);
Definition double Max(double x, double y);
Instantiation
Template
char *Max(char *x, char *y);
Argument Complex Max(Complex x, Complex y);
Deduction
Example
With every new type, we need to add an overloaded function in the library!
typename

Summary Issues in Max function


Same algorithm (compare two value using the appropriate operator
of the type and return the larger value)
Different code versions of these functions for strong type checking in
C++

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Max as Overload
#include <iostream>
Module 38 #include <cstring>
#include <cmath>
using namespace std;
Partha Pratim
Das
// Overloads
int Max(int x, int y) { return x > y ? x : y; }
Objectives & double Max(double x, double y) { return x > y ? x : y; }
Outline char *Max(char *x, char *y) { return strcmp(x, y) > 0 ? x : y; }

What is a int main() {


Template? int a = 3, b = 5, iMax;
double c = 2.1, d = 3.7, dMax;
Function
Template cout << "Max(" << a << ", " << b << ") = " << Max(a, b) << endl;
Definition cout << "Max(" << c << ", " << d << ") = " << Max(c, d) << endl;
Instantiation
Template
Argument char *s1 = new char[6], *s2 = new char[6];
Deduction strcpy(s1, "black"); strcpy(s2, "white");
Example cout << "Max(" << s1 << ", " << s2 << ") = " << Max(s1, s2) << endl;
strcpy(s1, "white"); strcpy(s2, "black");
typename cout << "Max(" << s1 << ", " << s2 << ") = " << Max(s1, s2) << endl;
Summary
return 0;
}

• Overloaded solutions work


• In some cases (C-string), similar algorithms have exceptions
• With every new type, a new overloaded Max is needed
• Can we make Max generic and make a library to work with future types?
• How about macros?
NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Max as a Macro

Module 38 #include <iostream>


using namespace std;
Partha Pratim
Das #define Max(x, y) (((x) > (y))? x: y)

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Max as a Macro:
Pitfalls
Module 38 #include <iostream>
#include <cstring>
Partha Pratim using namespace std;
Das
#define Max(x, y) (((x) > (y))? x: y)

Objectives & int main() {


Outline int a = 3, b = 5;
double c = 2.1, d = 3.7;
What is a
Template?
// Side Effects
Function cout << "Max(" << a << ", " << b << ") = "; // Output: Max(3, 5) = 6
Template cout << Max(a++, b++) << endl;
cout << "a = " << a << ", b = " << b << endl; // Output: a = 4, b = 7
Definition
Instantiation
Template
// C-String Comparison
Argument char *s1 = new char[6], *s2 = new char[6];
Deduction strcpy(s1, "black"); strcpy(s2, "white");
Example cout << "Max(" << s1 << ", " << s2 << ") = " << Max(s1, s2) << endl;
typename // Output: Max(black, white) = white

Summary strcpy(s1, "white"); strcpy(s2, "black");


cout << "Max(" << s1 << ", " << s2 << ") = " << Max(s1, s2) << endl;
// Output: Max(white, black) = black

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

Module 38 A function template


Partha Pratim describes how a function should be built
Das
supplies the definition of the function using some arbitrary types, (as
place holders)
Objectives &
Outline
a parameterized definition
What is a
Template? can be considered the definition for a set of overloaded versions of a
function
Function
Template is identified by the keyword template
Definition
Instantiation
followed by comma-separated list of parameter identifiers (each
Template preceded by keyword class or keyword typename)
Argument
Deduction enclosed between < and > delimiters
Example followed by the signature the function
typename
Note that every template parameter is a built-in type or class – type
Summary parameters

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Max as a Function Template

Module 38 #include <iostream>


using namespace std;
Partha Pratim
Das template<class T>
T Max(T x, T y) {
return x > y ? x : y;
Objectives & }
Outline
int main() {
What is a
int a = 3, b = 5, iMax;
Template?
double c = 2.1, d = 3.7, dMax;
Function
Template iMax = Max<int>(a, b);
cout << "Max(" << a << ", " << b << ") = " << iMax << endl;
Definition
// Output: Max(3, 5) = 5
Instantiation
Template
Argument dMax = Max<double>(c, d);
Deduction cout << "Max(" << c << ", " << d << ") = " << dMax << endl;
Example // Output: Max(2.1, 3.7) = 3.7
typename
return 0;
Summary }

• Max, now, knows the type


• Template type parameter T explicitly specified in instantiation of Max<int>, Max<double>

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Max as a Function Template:
Pitfall ”Side Effects” – Solved
Module 38 #include <iostream>
using namespace std;
Partha Pratim
Das template<class T>
T Max(T x, T y) {
return x > y ? x : y;
Objectives & }
Outline
int main() {
What is a
int a = 3, b = 5, iMax;
Template?

Function // Side Effects


Template cout << "Max(" << a << ", " << b << ") = ";
iMax = Max<int>(a++, b++);
Definition
cout << iMax << endl;
Instantiation
Template
// Output: Max(3, 5) = 5
Argument
Deduction cout << "a = " << a << ", b = " << b << endl;
Example // Output: a = 4, b = 6
typename
return 0;
Summary }

• Max is now a proper function call – no side effect

NPTEL MOOCs Programming in C++ Partha Pratim Das 11


Max as a Function Template:
Pitfall ”C-String Comparison” – Solved
Module 38 #include <iostream>
#include <cstring>
Partha Pratim using namespace std;
Das
template<class T>
T Max(T x, T y) { return x > y ? x : y; }
Objectives &
Outline template<> // Template specialization for ’char *’ type
char *Max<char *>(char *x, char *y) { return strcmp(x, y) > 0 ? x : y; }
What is a
Template?
int main() {
Function char *s1 = new char[6], *s2 = new char[6];
Template
strcpy(s1, "black"); strcpy(s2, "white");
Definition
cout << "Max(" << s1 << ", " << s2 << ") = " << Max<char>(s1, s2) << endl;
Instantiation
Template
// Output: Max(black, white) = white
Argument
Deduction strcpy(s1, "white"); strcpy(s2, "black");
Example cout << "Max(" << s1 << ", " << s2 << ") = " << Max<char>(s1, s2) << endl;
typename // Output: Max(black, white) = white

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Max as a Function Template:
Implicit Instantiation
Module 38 #include <iostream>
using namespace std;
Partha Pratim
Das template<class T>
T Max(T x, T y) {
return x > y ? x : y;
Objectives & }
Outline
int main() {
What is a
int a = 3, b = 5, iMax;
Template?
double c = 2.1, d = 3.7, dMax;
Function
Template iMax = Max(a, b); // Type ’int’ inferred from ’a’ and ’b’ parameters types
cout << "Max(" << a << ", " << b << ") = " << iMax << endl;
Definition
// Output: Max(3, 5) = 5
Instantiation
Template
Argument dMax = Max(c, d); // Type ’double’ inferred from ’c’ and ’d’ parameters types
Deduction cout << "Max(" << c << ", " << d << ") = " << dMax << endl;
Example // Output: Max(2.1, 3.7) = 3.7
typename
return 0;
Summary }

• 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Template Argument Deduction:
Implicit Instantiation
Module 38 Each item in the template parameter list is a template argument
Partha Pratim When a template function is invoked, the values of the template arguments
Das are determined by seeing the types of the function arguments
Objectives & template<class T> T Max(T x, T y);
Outline template<> char *Max<char *>(char *x, char *y);
template <class T, int size> Type Max(T x[size]);
What is a
Template? int a, b; Max(a, b); // Binds to Max<int>(int, int);
double c, d; Max(c, d); // Binds to Max<double>(double, double);
Function char *s1, *s2; Max(s1, s2); // Binds to Max<char*>(char*, char*);
Template
Definition int pval[9]; Max(pval); //Error!
Instantiation
Template
Argument Three kinds of conversions are allowed
Deduction
Example L-value transformation (for example, Array-to-pointer conversion)
typename
Qualification conversion
Conversion to a base class instantiation from a class template
Summary
If the same template parameter are found for more than one function
argument, template argument deduction from each function argument must
be the same

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Max as a Function Template:
With User-Defined Class
#include <iostream>
Module 38 #include <cmath>
#include <cstring>
using namespace std;
Partha Pratim
Das
class Complex { double re_; double im_;
public:
Objectives & Complex(double re = 0.0, double im = 0.0) : re_(re), im_(im) {};
Outline double norm() const { return sqrt(re_*re_+im_*im_); }
friend bool operator>(const Complex& c1, const Complex& c2) {
What is a return c1.norm() > c2.norm();
Template? }
friend ostream& operator<<(ostream& os, const Complex& c) {
Function os << "(" << c.re_ << ", " << c.im_ << ")"; return os;
Template }
Definition };
Instantiation template<class T> T Max(T x, T y) { return x > y ? x : y; }
Template
Argument template<> char *Max<char *>(char *x, char *y) { return strcmp(x, y) > 0 ? x : y; }
Deduction
Example int main() { Complex c1(2.1, 3.2), c2(6.2, 7.2);
typename cout << "Max(" << c1 << ", " << c2 << ") = " << Max(c1, c2) << endl;
// Output: Max((2.1, 3.2), (6.2, 7.2)) = (6.2, 7.2)
Summary
return 0;
}

• 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

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Max as a Function Template:
Overloads
Module 38 #include <iostream>
#include <cstring>
Partha Pratim using namespace std;
Das
template<class T> T Max(T x, T y) { return x > y ? x : y; }

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 }

• Template function can be overloaded


Summary
• A template parameter can be non-type (int) constant

NPTEL MOOCs Programming in C++ Partha Pratim Das 16


Swap as a Function Template

Module 38 #include <iostream>


#include <string>
Partha Pratim using namespace std;
Das
template<class T> void Swap(T& one, T& other)
{
Objectives & T temp;
Outline temp = one; one = other; other = temp;
}
What is a
int main() {
Template?
int i = 10, j = 20;
Function cout << "i = " << i << ", j = " << j << endl;
Template Swap(i, j);
cout << "i = " << i << ", j = " << j << endl;
Definition
Instantiation
Template
string s1("abc"), s2("def");
Argument
Deduction cout << "s1 = " << s1 << ", s2 = " << s2 << endl;
Example Swap(s1, s2);
typename cout << "s1 = " << s1 << ", s2 = " << s2 << endl;

Summary return 0;
}

• The traits of type variable T include


default constructor (T::T()) and
copy assignment operator (T operator=(const T&))
• Our template function cannot be called swap, as std namespace has such a function

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


typename Keyword

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 18


Module Summary

Module 38

Partha Pratim Introduced the templates in C++


Das
Discussed function templates as generic algorithmic
Objectives &
Outline solution for code reuse
What is a
Template?
Explained templates argument deduction for implicit
Function
instantiation
Template
Definition
Illustrated with examples
Instantiation
Template
Argument
Deduction
Example

typename

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 19


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 20


Module 39

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 39

Partha Pratim Understand Templates in C++


Das

Objectives &
Outline

What is a
Template?

Function
Template

Class
Template
Definition
Instantiation
Partial Template
Instantiation &
Default
Template
Parameters
Inheritance

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 39

Partha Pratim What is a Template?


Das
Function Template
Objectives &
Outline
Function Template Definition
What is a
Instantiation
Template? Template Argument Deduction
Function Example
Template

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


What is a Template?:
RECAP (Module 38)
Module 39

Partha Pratim Templates are specifications of a collection of functions or


Das
classes which are parameterized by types
Objectives &
Outline Examples:
What is a Function search, min etc.
Template?
The basic algorithms in these functions are the same
Function
Template independent of types
Class
Yet, we need to write different versions of these functions
Template for strong type checking in C++
Definition
Instantiation Classes list, queue etc.
Partial Template
Instantiation &
Default
The data members and the methods are almost the same
Template
Parameters
for list of numbers, list of objects
Inheritance Yet, we need to define different classes
Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


Function Template:
Code reuse in Algorithms: RECAP (Module 38)
Module 39
We need to compute the maximum of two values that can be of:
Partha Pratim int
Das
double
char * (C-String)
Objectives &
Outline Complex (user-defined class for complex numbers)
What is a
...
Template? We can do this with overloaded Max functions:
Function
Template int Max(int x, int y);
double Max(double x, double y);
Class
Template char *Max(char *x, char *y);
Definition Complex Max(Complex x, Complex y);
Instantiation
Partial Template
Instantiation & With every new type, we need to add an overloaded function in the library!
Default
Template
Parameters Issues in Max function
Inheritance
Same algorithm (compare two value using the appropriate operator
Summary of the type and return the larger value)
Different code versions of these functions for strong type checking in
C++

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


Class Template:
Code Reuse in Data Structure
Module 39 Solution of several problems needs stack (LIFO)
Reverse string (char)
Partha Pratim
Das Convert infix expression to postfix (char)
Evaluate postfix expression (int / double / Complex ...)
Objectives & Depth-first traversal (Node *)
Outline ...
What is a
Template?
Solution of several problems needs queue (FIFO)
Task Scheduling (Task *)
Function
Template Process Scheduling (Process *)
...
Class
Template Solution of several problems needs list (ordered)
Definition
Instantiation Implementing stack, queue (int / char / ...)
Partial Template
Instantiation & Implementing object collections (UDT)
Default
Template
...
Parameters
Inheritance Solution of several problems needs ...
Summary Issues in Data Structure
Data Structures are generic - same interface, same algorithms
C++ implementations are different due to element type

NPTEL MOOCs Programming in C++ Partha Pratim Das 6


Stack of char and int

Module 39 class Stack { class Stack {


char data_[100]; // Has type int data_[100]; // Has type
Partha Pratim int top_; int top_;
Das public: public:
Stack() :top_(-1) {} Stack() :top_(-1) {}
~Stack() {} ~Stack() {}
Objectives &
Outline void push(const char& item) // Has type void push(const int& item) // Has type
{ data_[++top_] = item; } { data_[++top_] = item; }
What is a
Template?
void pop() void pop()
Function { --top_; } { --top_; }
Template
const char& top() const // Has type const int& top() const // Has type
Class { return data_[top_]; } { return data_[top_]; }
Template
Definition bool empty() const bool empty() const
Instantiation { return top_ == -1; } { return top_ == -1; }
Partial Template }; };
Instantiation &
Default • Stack of char • Stack of int
Template
Parameters • Can we combine these Stack codes using a type variable T?
Inheritance

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Class Template

Module 39 A class template


Partha Pratim describes how a class should be built
Das
Supplies the class description and the definition of the member
functions using some arbitrary type name, (as a place holder)
Objectives &
Outline is a:
What is a parameterized type with
Template? parameterized member functions
Function
Template can be considered the definition for a unbounded set of class types
is identified by the keyword template
Class
Template followed by comma-separated list of parameter identifiers (each
Definition
Instantiation
preceded by keyword class or keyword typename)
Partial Template enclosed between < and > delimiters
Instantiation &
Default followed by the definition of the class
Template
Parameters
Inheritance
is often used for container classes
Note that every template parameter is a built-in type or class – type
Summary
parameters

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Stack as a Class Template:
Stack.h
Module 39 template<class T>
class Stack {
Partha Pratim T data_[100];
Das int top_;
public:
Stack() :top_(-1) {}
Objectives & ~Stack() {}
Outline
void push(const T& item)
What is a
{ data_[++top_] = item; }
Template?

Function void pop()


Template { --top_; }

Class const T& top() const


Template { return data_[top_]; }
Definition
Instantiation bool empty() const
Partial Template { return top_ == -1; }
Instantiation & };
Default
Template
Parameters • Stack of type variable T
Inheritance • The traits of type variable T include
copy assignment operator (T operator=(const T&))
Summary • We do not call our template class as stack because std namespace has a class stack

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Reverse String:
Using Stack template
Module 39 #include <iostream>
#include "Stack.h"
Partha Pratim using namespace std;
Das
int main() {
char str[10] = "ABCDE";
Objectives &
Outline Stack<char> s; // Instantiated for char
What is a
for (unsigned int i = 0; i < strlen(str); ++i)
Template?
s.push(str[i]);
Function
Template cout << "Reversed String: ";
while (!s.empty()) {
Class cout << s.top();
Template s.pop();
Definition }
Instantiation
Partial Template return 0;
Instantiation & }
Default
Template
Parameters • Stack of type char
Inheritance

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 10


Postfix Expression Evaluation:
Using Stack template
Module 39 #include <iostream>
#include "Stack.h"
Partha Pratim using namespace std;
Das
int main() {
// Postfix expression: 1 2 3 * + 9 -
Objectives & unsigned int postfix[] = { ’1’, ’2’, ’3’, ’*’, ’+’, ’9’, ’-’ }, ch;
Outline
Stack<int> s; // Instantiated for int
What is a
Template?
for (unsigned int i = 0; i < sizeof(postfix) / sizeof(unsigned int); ++i) {
Function ch = postfix[i];
Template if (isdigit(ch)) { s.push(ch - ’0’); }
else {
Class int op1 = s.top(); s.pop();
Template int op2 = s.top(); s.pop();
Definition switch (ch) {
Instantiation case ’*’: s.push(op2 * op1); break;
Partial Template case ’/’: s.push(op2 / op1); break;
Instantiation & case ’+’: s.push(op2 + op1); break;
Default case ’-’: s.push(op2 - op1); break;
Template
Parameters }
Inheritance }
}
Summary cout << "\nEvaluation " << s.top();

return 0;
}

• Stack of type int


NPTEL MOOCs Programming in C++ Partha Pratim Das 11
Template Parameter Traits

Module 39 Parameter Types


Partha Pratim may be of any type (including user defined types)
Das
may be parameterized types, (that is, templates)
MUST support the methods used by the template functions:
Objectives &
Outline
What are the required constructors?
What is a The required operator functions?
Template? What are the necessary defining operations?
Function
Template

Class
Template
Definition
Instantiation
Partial Template
Instantiation &
Default
Template
Parameters
Inheritance

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 12


Function Template Instantiation:
RECAP (Module 38)
Module 39 Each item in the template parameter list is a template argument
Partha Pratim When a template function is invoked, the values of the template arguments
Das are determined by seeing the types of the function arguments
Objectives & template<class T> T Max(T x, T y);
Outline template<> char *Max<char *>(char *x, char *y);
template <class T, int size> Type Max(T x[size]);
What is a
Template? int a, b; Max(a, b); // Binds to Max<int>(int, int);
double c, d; Max(c, d); // Binds to Max<double>(double, double);
Function char *s1, *s2; Max(s1, s2); // Binds to Max<char*>(char*, char*);
Template
int pval[9]; Max(pval); //Error!
Class
Template
Definition
Three kinds of conversions are allowed
Instantiation L-value transformation (for example, Array-to-pointer conversion)
Partial Template
Instantiation & Qualification conversion
Default
Template Conversion to a base class instantiation from a class template
Parameters
Inheritance If the same template parameter are found for more than one function
Summary argument, template argument deduction from each function argument must
be the same

NPTEL MOOCs Programming in C++ Partha Pratim Das 13


Class Template Instantiation

Module 39 Class Template is instantiated only when it is required:


Partha Pratim template<class T> class Stack; is a forward declaration
Das
Stack<char> s; is an error
Stack<char> *ps; is okay
Objectives &
Outline void ReverseString(Stack<char>& s, char *str); is okay
What is a Class template is instantiated before
Template?
An object is defined with class template instantiation
Function
Template If a pointer or a reference is dereferenced (for example, a method is
invoked)
Class
Template A template definition can refer to a class template or its instances but a
Definition
Instantiation
non-template can only refer to template instances
Partial Template
Instantiation &
Default
Template
Parameters
Inheritance

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 14


Class Template Instantiation Example
#include <iostream>
Module 39 using namespace std;

template<class T> class Stack; // Forward declaration


Partha Pratim
Das
void ReverseString(Stack<char>& s, char *str); // Stack template definition is not needed

Objectives & template<class T> // Definition


Outline class Stack { T data_[100]; int top_;
public: Stack() :top_(-1) {} ~Stack() {}
What is a
Template? void push(const T& item) { data_[++top_] = item; }
void pop() { --top_; }
Function const T& top() const { return data_[top_]; }
Template bool empty() const { return top_ == -1; }
Class };
Template int main() {
char str[10] = "ABCDE";
Definition
Stack<char> s; // Stack template definition is needed
Instantiation
Partial Template
Instantiation & ReverseString(s, str);
Default
Template
Parameters return 0;
Inheritance }
void ReverseString(Stack<char>& s, char *str) { // Stack template definition is needed
Summary for (unsigned int i = 0; i < strlen(str); ++i) s.push(str[i]);

cout << "Reversed String: ";


while (!s.empty()) { cout << s.top(); s.pop(); }
}

NPTEL MOOCs Programming in C++ Partha Pratim Das 15


Partial Template Instantiation and
Default Template Parameters
#include <iostream>
Module 39 #include <string>
using namespace std;
Partha Pratim
template<class T1 = int, class T2 = string> // Version 1 with default parameters
Das
class Student { T1 roll_; T2 name_;
public: Student(T1 r, T2 n) : roll_(r), name_(n) {}
Objectives & void Print() const { cout << "Version 1: (" << name_ << ", " << roll_ << ")" << endl; }
Outline };
template<class T1> // Version 2: Partial Template Specialization
What is a class Student<T1, char *> { T1 roll_; char *name_;
Template? public: Student(T1 r, char *n) : roll_(r), name_(strcpy(new char[strlen(n) + 1], n)) {}
void Print() const { cout << "Version 2: (" << name_ << ", " << roll_ << ")" << endl; }
Function };
Template int main() {
Class Student<int, string> s1(2, "Ramesh"); // Version 1: T1 = int, T2 = string
Template Student<int> s2(11, "Shampa"); // Version 1: T1 = int, defa T2 = string
Student<> s3(7, "Gagan"); // Version 1: defa T1 = int, defa T2 = string
Definition
Student<string> s4("X9", "Lalita"); // Version 1: T1 = string, defa T2 = string
Instantiation
Student<int, char*> s5(3, "Gouri"); // Version 2: T1 = int, T2 = char*
Partial Template
Instantiation &
Default s1.Print(); s2.Print(); s3.Print(); s4.Print(); s5.Print();
Template
Parameters
Inheritance return 0;
}
Summary -----
Version 1: (Ramesh, 2)
Version 1: (Shampa, 11)
Version 1: (Gagan, 7)
Version 1: (Lalita, X9)
Version 2: (Gouri, 3)
NPTEL MOOCs Programming in C++ Partha Pratim Das 16
Templates and Inheritance:
Example (List.h)
#ifndef __LIST_H
Module 39 #define __LIST_H

#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

NPTEL MOOCs Programming in C++ Partha Pratim Das 17


Templates and Inheritance:
Example (Set.h)
#ifndef __SET_H
Module 39 #define __SET_H

#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

NPTEL MOOCs Programming in C++ Partha Pratim Das 18


Templates and Inheritance:
Example (BoundSet.h)
#ifndef __BOUND_SET_H
Module 39 #define __BOUND_SET_H

#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

Class template<class T> BoundSet<T>::BoundSet(const T &lower, const T &upper)


Template : min(lower), max(upper) { }
template<class T> void BoundSet<T>::add(const T &val) {
Definition
if (find(val)) return;
Instantiation
if ((val <= max) && (val >= min))
Partial Template
Instantiation & Set<T>:: add(val);
Default }
Template
Parameters #endif // __BOUND_SET_H
Inheritance
• BoundSet is a specialization of Set
Summary • BoundSet is a set of bounded items

NPTEL MOOCs Programming in C++ Partha Pratim Das 19


Templates and Inheritance:
Example (Bounded Set Application)
#include <iostream>
Module 39 using namespace std;
#include "BoundSet.h"
Partha Pratim
int main() {
Das
int i;
BoundSet<int> bsi(3, 21);
Objectives & Set<int> *setptr = &bsi;
Outline
for (i = 0; i < 25; i++) setptr->add(i);
What is a
Template? if (bsi.find(4))
cout << "We found an expected value\n";
Function
Template if (bsi.find(0) || bsi.find(25)) {
Class cout << "We found an Unexpected value\n";
Template return -1;
}
Definition
else
Instantiation
cout << "We found NO unexpected value\n";
Partial Template
Instantiation &
Default return 0;
Template
Parameters }
Inheritance -----
We found an expected value
Summary We found NO unexpected value

• Uses BoundSet to maintain and search elements

NPTEL MOOCs Programming in C++ Partha Pratim Das 20


Module Summary

Module 39

Partha Pratim Introduced the templates in C++


Das
Discussed class templates as generic solution for data
Objectives &
Outline structure reuse
What is a
Template?
Explained partial template instantiation and default
Function
template parameters
Template
Demonstrated templates on inheritance hierarchy
Class
Template Illustrated with examples
Definition
Instantiation
Partial Template
Instantiation &
Default
Template
Parameters
Inheritance

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 21


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 22


Module 40

Partha Pratim
Das Module 40: Programming C++
Objectives & Closing Comments
Outline

Course
Summary

Key Take-back Partha Pratim Das


Prepare for
Examination
Department of Computer Science and Engineering
Road Forward Indian Institute of Technology, Kharagpur
Summary
[email protected]

Tanwi Mallick
Srijoni Majumdar
Himadri B G S Bhuyan

NPTEL MOOCs Programming in C++ Partha Pratim Das 1


Module Objectives

Module 40

Partha Pratim Review C++ Course


Das
Information for Examination
Objectives &
Outline What next?
Course
Summary

Key Take-back

Prepare for
Examination

Road Forward

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 2


Module Outline

Module 40

Partha Pratim Course Summary


Das
Key Take-back
Objectives &
Outline Prepare for Examination
Course
Summary Road Forward
Key Take-back

Prepare for
Examination

Road Forward

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 3


What we covered

Module 40 Programming in C++ is Fun: Build and execute a C


Partha Pratim programs in C++, Write equivalent programs in C++
Das
C++ as Better C: Procedural Extensions of C
Objectives &
Outline Object-Oriented Programming in C++: Classes,
Course Encapsulation, Overloading, friend, static, and namespace
Summary

Key Take-back Inheritance: Generalization / Specialization of Object


Prepare for Modeling in C++
Examination

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 4


What we did not cover?

Module 40 Functors: Function Objects


Partha Pratim
Das
STL: Standard Template Library of C++
Resource Management: Smart Pointers, Memory
Objectives &
Outline Handling
Course
Summary C++ Coding Styles: How to write good code?
Key Take-back Design Patterns: Reusable Designs
Prepare for
Examination Mixing C and C++: Smart Pointers, Memory Handling
Road Forward Source Code Management: How to organize files,
Summary libraries?
C++ Tools: Analysis, Version Control etc.
...

NPTEL MOOCs Programming in C++ Partha Pratim Das 5


What have we learnt?

Module 40
C++ is multi-paradigm
Partha Pratim
Das Procedural: Better C
Object-Oriented: Encapsulation, Inheritance, and Polymorphism
Objectives & Generic: Templates
Outline

Course Reuse is Key


Summary Macros
Key Take-back Library functions
Prepare for
Function Overloading (Static Polymorphism)
Examination Inheritance & Dynamic Polymorphism
Templates & STL
Road Forward
Design Patterns
Summary
Designing good data types is a key for good programming in C++
While programming in C++, we should keep an eye on:
Efficiency
Safety
Clarity

Do not write C-style programs using C++ compiler


NPTEL MOOCs Programming in C++ Partha Pratim Das 6
Prepare for Examination

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 7


Road Forward

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)

NPTEL MOOCs Programming in C++ Partha Pratim Das 8


Module Summary

Module 40

Partha Pratim Course on C++ concluded


Das

Objectives &
Outline

Course
Summary

Key Take-back

Prepare for
Examination

Road Forward

Summary

NPTEL MOOCs Programming in C++ Partha Pratim Das 9


Instructor and TAs

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

NPTEL MOOCs Programming in C++ Partha Pratim Das 10

You might also like