You are on page 1of 24

Module 40

Intructors: Abir
Das and
Sourangshu
Bhattacharya
Module 40: Programming in C++
Objectives &
Outlines Functors: Function Objects
Function Pointers
Callback
qsort
Issues

Functors Intructors: Abir Das and Sourangshu Bhattacharya


Basic Functor
Department of Computer Science and Engineering
Simple Example
Examples from STL
Indian Institute of Technology, Kharagpur
Function Pointer
{abir, sourangshu}@cse.iitkgp.ac.in

Slides taken from NPTEL course on Programming in Modern C++

by Prof. Partha Pratim Das

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 1


Module Objectives

Module 40
Intructors: Abir
Das and
Sourangshu
• Understand the Function Objects or Functor
Bhattacharya
• Study the utility of functor in design, especially in STL
Objectives &
Outlines

Function Pointers
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 2


Module Outline

Module 40
Intructors: Abir
Das and
Sourangshu
Bhattacharya
1 Function Pointers
Objectives &
Outlines
Callback
qsort
Function Pointers
Callback Issues
qsort
Issues

Functors
Basic Functor
Simple Example
2 Functors in C++
Examples from STL Basic Functor
Function Pointer
Simple Example
Examples from STL
Function Pointer

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 3


Function Pointers

Module 40
Intructors: Abir
Das and
Sourangshu
• Points to the address of a function
Bhattacharya
◦ Ordinary C functions
Objectives & ◦ Static C++ member functions
Outlines
◦ Non-static C++ member functions
Function Pointers
Callback • Points to a function with a specific signature
qsort
Issues ◦ List of Calling Parameter Types
Functors ◦ Return-Type
Basic Functor
Simple Example ◦ Calling Convention
Examples from STL
Function Pointer

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 4


Function Pointers in C

Module 40
Intructors: Abir
• Define a Function Pointer
Das and
Sourangshu
int (*pt2Function) (int, char, char);
Bhattacharya

Objectives &
• Calling Convention
Outlines int DoIt (int a, char b, char c);
Function Pointers
int DoIt (int a, char b, char c) {
Callback
printf ("DoIt\n");
qsort return a+b+c;
Issues }
Functors • Assign Address to a Function Pointer
Basic Functor pt2Function = &DoIt; // OR
Simple Example pt2Function = DoIt;
Examples from STL
Function Pointer • Call the Function pointed by the Function Pointer
int result = (*pt2Function) (12, ’a’, ’b’);

• Compare Function Pointers


if (pt2Function == &DoIt) {
printf ("pointer points to DoIt\n");
}

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 5


Function Pointers in C
Direct Function Pointer Using typedef
Module 40
Intructors: Abir
Das and #include <stdio.h> #include <stdio.h>
Sourangshu
Bhattacharya
int (*pt2Function) (int, char, char); typedef int (*pt2Function) (int, char, char);
Objectives &
int DoIt (int a, char b, char c); int DoIt (int a, char b, char c);
Outlines
int main() { int main() {
Function Pointers
pt2Function = DoIt; // &DoIt pt2Function f = &DoIt; // DoIt
Callback
qsort
Issues
int result = (*pt2Function)(12, ’a’, ’b’); int result = f(12, ’a’, ’b’);
Functors
printf("%d", result); printf("%d", result);
Basic Functor
Simple Example
Examples from STL
return 0; return 0;
Function Pointer
} }
int DoIt (int a, char b, char c) { int DoIt (int a, char b, char c) {
printf ("DoIt\n"); printf ("DoIt\n");

return a + b + c; return a + b + c;
} }
DoIt DoIt
207 207

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 6


Function Reference In C++

Module 40
Intructors: Abir
• Define a Function Pointer
Das and int (A::*pt2Member)(float, char, char);
Sourangshu
Bhattacharya
• Calling Convention
Objectives &
Outlines class A {
int DoIt (float a, char b, char c) {
Function Pointers
Callback
cout << "A::DoIt" << endl; return a+b+c; }
qsort
};
Issues

Functors • Assign Address to a Function Pointer


Basic Functor
pt2Member = &A::DoIt;
Simple Example
Examples from STL
Function Pointer • Call the Function pointed by the Function Pointer
A instance1;
int result = (instance1.*pt2Member)(12, ’a’, ’b’);

• Compare Function Pointers


if (pt2Member == &A::DoIt) {
cout <<"pointer points to A::DoIt" << endl;
}
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 7
Function Pointer: Operations and Programming Techniques

Module 40
Intructors: Abir
Das and
Sourangshu
• Operations
Bhattacharya
◦ Assign an Address to a Function Pointer
Objectives & ◦ Compare two Function Pointers
Outlines
◦ Call a Function using a Function Pointer
Function Pointers
Callback ◦ Pass a Function Pointer as an Argument
qsort
Issues
◦ Return a Function Pointer
Functors
◦ Arrays of Function Pointers
Basic Functor
Simple Example
• Programming Techniques
Examples from STL
Function Pointer
◦ Replacing switch/if-statements
◦ Realizing user-defined late-binding, or
▷ Functions in Dynamically Loaded Libraries
▷ Virtual Functions
◦ Implementing callbacks

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 8


Function Pointers: Replace Switch/ IF Statements

Module 40
# include < iostream >
Intructors: Abir using namespace std ;
Das and
Sourangshu // The four arithmetic operations
Bhattacharya float Plus ( float a , float b ) { return a + b ; }
float Minus ( float a , float b ) { return a - b ; }
Objectives &
Outlines float Multiply ( float a , float b ) { return a * b ; }
Function Pointers float Divide ( float a , float b ) { return a / b ; }
Callback int main () {
qsort int ch , a , b ;
Issues
cout << " Enter 0 for add , 1 for sub , 2 for mult and 3 for div : " ;
Functors
cin >> ch ;
Basic Functor
Simple Example
cout << " Enter 2 numbers : " ;
Examples from STL cin >> a >> b ;
Function Pointer switch ( ch ) {
case 0: cout << Plus (a , b ) << endl ; break ;
case 1: cout << Minus (a , b ) << endl ; break ;
case 2: cout << Multiply (a , b ) << endl ; break ;
case 3: cout << Divide (a , b ) << endl ; break ;
case 4: cout << " Enter valid choice " << endl ;
}
return 0;
}S20202: Software Engineering
C Intructors: Abir Das and Sourangshu Bhattacharya 9
Function Pointers: Replace Switch/ IF Statements

Module 40 # include < iostream >


Intructors: Abir
Das and
using namespace std ;
Sourangshu // The four arithmetic operations
Bhattacharya
float Plus ( float a , float b ) { return a + b ; }
Objectives &
float Minus ( float a , float b ) { return a - b ; }
Outlines float Multiply ( float a , float b ) { return a * b ; }
Function Pointers float Divide ( float a , float b ) { return a / b ; }
Callback int main () {
qsort
Issues
float (* OpPtr [4]) ( float , float ) = { Plus , Minus , Multiply , Divide };
int ch , a , b ;
Functors
Basic Functor
cout << " Enter 0 for add , 1 for sub , 2 for mult and 3 for div : " ;
Simple Example cin >> ch ;
Examples from STL cout << " Enter 2 numbers : " ;
Function Pointer
cin >> a >> b ;
cout << (* OpPtr [ ch ]) (a , b ) << endl ;
return 0;
}

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 10


Example: Callback, Function Pointers

Module 40
Intructors: Abir
Das and
Sourangshu
• It is a Common C Feature
Bhattacharya
# include < iostream >
Objectives & using namespace std ;
Outlines

Function Pointers void A () {


Callback
cout << " Hello " << endl ;
qsort
Issues
}
// Function pointer as argument
Functors
Basic Functor
void B ( void (* fptr ) () ) {
Simple Example // Calling back function that fptr points to
Examples from STL
fptr () ;
Function Pointer
}
int main () {
void (* fp ) () = A ;
B ( fp ) ; // Or simply B ( A )
return 0;
}

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 11


Function Pointers: Callback: qsort to Quick Sort

Module 40 void qsort(void *base, // Pointer to the first element of the array to be sorted
Intructors: Abir
Das and size_t nitems, // Number of elements in the array pointed by base
Sourangshu
Bhattacharya
size_t size, // Size in bytes of each element in the array
int (*compar)(const void *, const void*)); // Function that compares two elements
Objectives &
Outlines
int CmpFunc(const void* a, const void* b) { // Compare function for int
Function Pointers int ret = (*(const int*)a > *(const int*) b)? 1:
Callback
qsort
(*(const int*)a == *(const int*) b)? 0: -1;
Issues return ret;
Functors }
Basic Functor
Simple Example int main() {
Examples from STL
Function Pointer
int field[10];

for(int c = 10; c>0; c--)


field[10-c] = c;

qsort((void*) field, 10, sizeof(field[0]), CmpFunc);


}

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 12


Function Pointers: Issues

Module 40
Intructors: Abir
Das and
Sourangshu
• No value semantics
Bhattacharya
• Weak type checking
Objectives &
Outlines
• Two function pointers having identical signature are necessarily indistinguishable
Function Pointers • No encapsulation for parameters
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 13


Functors or Function Objects

Module 40
Intructors: Abir • Smart Functions
Das and
Sourangshu ◦ Functors are functions with a state
Bhattacharya
◦ Functors encapsulate C / C++ function pointers
Objectives &
Outlines ▷ Uses templates and
Function Pointers ▷ Engages polymorphism
Callback
qsort • Has its own Type
Issues

Functors
◦ A class with zero or more private members to store the state and an overloaded
Basic Functor operator() to execute the function
Simple Example
Examples from STL • Usually faster than ordinary Functions
Function Pointer

• Can be used to implement callbacks


• Provides the basis for Command Design Pattern

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 14


Basic Functor

Module 40
Intructors: Abir
Das and
Sourangshu
• Any class that overloads the function call operator:
Bhattacharya
◦ void operator()();
Objectives & ◦ int operator()(int, int);
Outlines
◦ double operator()(int, double);
Function Pointers
Callback ◦ ...
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 15


Functors: Simple Example

Module 40
Intructors: Abir • Consider the code below
Das and
Sourangshu int AdderFunction(int a, int b) { // A function
Bhattacharya return a + b;
Objectives &
}
Outlines

Function Pointers class AdderFunctor {


Callback public:
qsort int operator()(int a, int b) { // A functor
Issues
return a + b;
Functors
}
Basic Functor
Simple Example
};
Examples from STL
Function Pointer
int main() {
int x = 5;
int y = 7;
int z = AdderFunction(x, y); // Function invocation

AdderFunctor aF;
int w = aF(x, y); // aF.operator()(x, y); -- Functor invocation
}
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 16
Functors: Examples from STL: Function Pointer for Functor

Module 40 • Fill a vector with random numbers


Intructors: Abir
Das and ◦ generate algorithm
Sourangshu #include <algorithm>
Bhattacharya
template <class ForwardIterator, class Generator>
Objectives &
void generate(ForwardIterator first, ForwardIterator last, Generator gen) {
Outlines while (first != last) {
*first = gen();
Function Pointers
++first;
Callback
qsort
}
Issues
}
Functors
▷ first, last: Iterators are defined for a range in the sequence. ”[” or ”]” means include the element and ”(” or
Basic Functor
”)” means exclude the element. ForwardIterator has a range [first,last) spanning from first element to
Simple Example
the element before the last
Examples from STL ▷ gen: Generator function that is called with no arguments and returns some value of a type convertible to those
Function Pointer pointed by the iterators
▷ This can either be a function pointer or a function object
◦ Function Pointer rand as Function Object
#include <cstdlib>

// int rand (void);

vector<int> V(100);
generate(V.begin(), V.end(), rand);
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 17
Functors: Examples from STL

Module 40 • Sort a vector of UDTs


Intructors: Abir # include < iostream >
Das and
Sourangshu # include < vector >
Bhattacharya # include < string >
Objectives &
# include < algorithm >
Outlines using namespace std ;
Function Pointers class Student {
Callback public :
qsort float CGPA ;
Issues
string RollNo ;
Functors
Student ( string RN , float CG ) : RollNo ( RN ) , CGPA ( CG ) {};
Basic Functor
Simple Example
};
Examples from STL
Function Pointer
int main () {
vector < Student > students { Student ( " 18 CS10065 " ,8.5) ,
Student ( " 19 CS30008 " ,8.3) ,
Student ( " 17 CS10024 " ,8.9) };
sort ( students . begin () , students . end () ) ;
return 0;
}

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 18


Functors: Examples from STL

Module 40 • Sort a vector of UDTs


Intructors: Abir # include < iostream >
Das and
Sourangshu # include < vector >
Bhattacharya # include < string >
Objectives &
# include < algorithm >
Outlines using namespace std ;
Function Pointers class Student {
Callback public :
qsort float CGPA ;
Issues
string RollNo ;
Functors
Student ( string RN , float CG ) : RollNo ( RN ) , CGPA ( CG ) {};
Basic Functor
Simple Example
};
Examples from STL
Function Pointer
int main () {
vector < Student > students { Student ( " 18 CS10065 " ,8.5) ,
Student ( " 19 CS30008 " ,8.3) ,
Student ( " 17 CS10024 " ,8.9) };
sort ( students . begin () , students . end () ) ;
return 0;
}
• Compilation error!
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 19
CPPReference about sort

Module 40
Intructors: Abir
Das and
Sourangshu
Bhattacharya

Objectives &
Outlines

Function Pointers
Callback
qsort
Issues

Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 20


Functors: Examples from STL

Module 40 # include < iostream >


Intructors: Abir
Das and
# include < vector >
Sourangshu # include < string >
Bhattacharya
# include < algorithm >
Objectives &
using namespace std ;
Outlines class Student {
Function Pointers public :
Callback float CGPA ;
qsort
Issues
string RollNo ;
Student ( string RN , float CG ) : RollNo ( RN ) , CGPA ( CG ) {};
Functors
Basic Functor
bool operator <( const Student & rhs ) {
Simple Example return this - > CGPA < rhs . CGPA ;
Examples from STL }
Function Pointer
};

• Continued in next slide

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 21


Functors: Examples from STL

Module 40 int main () {


Intructors: Abir
Das and
vector < Student > students { Student ( " 18 CS10065 " ,8.5) ,
Sourangshu Student ( " 19 CS30008 " ,8.3) ,
Bhattacharya
Student ( " 17 CS10024 " ,8.9) };
Objectives &
sort ( students . begin () , students . end () ) ;
Outlines for ( auto st : students ) {
Function Pointers cout << st . RollNo << " , " << st . CGPA << endl ;
Callback }
qsort
Issues
return 0;
}
Functors
Basic Functor
Simple Example
Examples from STL
Function Pointer

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 22


Functors: Examples from STL

Module 40 # include < iostream >


Intructors: Abir
Das and
# include < vector >
Sourangshu # include < string >
Bhattacharya
# include < algorithm >
Objectives &
using namespace std ;
Outlines class Student {
Function Pointers public :
Callback float CGPA , SGPA ;
qsort
Issues
string RollNo ;
Student ( string RN , float CG , float SG ) : RollNo ( RN ) , CGPA ( CG ) , SGPA ( SG ) {};
Functors
Basic Functor
bool operator <( const Student & rhs ) {
Simple Example return this - > CGPA < rhs . CGPA ;
Examples from STL }
Function Pointer
};
class SGPAComp {
public :
bool operator () ( const Student & lhs , const Student & rhs ) {
return lhs . SGPA < rhs . SGPA ;
}
};
• Continued in next slide
CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 23
Functors: Examples from STL

Module 40 int main () {


Intructors: Abir
Das and
vector < Student > students { Student ( " 18 CS10065 " ,8.5 ,9.1) ,
Sourangshu Student ( " 19 CS30008 " ,8.3 ,7.8) ,
Bhattacharya
Student ( " 17 CS10024 " ,8.9 ,8.5) };
Objectives &
// Sort using the functor to compare SGPAs
Outlines sort ( students . begin () , students . end () , SGPAComp () ) ;
Function Pointers
Callback for ( auto st : students ) {
qsort
Issues
cout << st . RollNo << " , " << st . CGPA << " , "
<< st . SGPA << endl ;
Functors
Basic Functor
}
Simple Example return 0;
Examples from STL }
Function Pointer

CS20202: Software Engineering Intructors: Abir Das and Sourangshu Bhattacharya 24

You might also like