C++ Cs
C++ Cs
LEARNING OBJECTIVES
After going through this chapter, you will be able to
Describe the usage of main 0 function in a Ct+ program
Explain function prototyping
Distinguish call by reference and return by reference mechanisms
O Discuss inline functions
Determine how default arguments are used with functions
Explain recursion with the help of an example
Demonstrate how function overloading is used in a C++ program
List the various match library functions
4.1 INTRODUCTION
We know that functions play an important role in C program development. Dividing a program into functions is one of
the major principles of top-down, structured programming. Another advantage of using functions is that it is possible to
reduce the size of a program by calling and using them at different places in the program.
Recall that we have used a syntax similar to the following in developing C programs
/* Function call *7
show()
called.
control is
transferred
main program
when the closing brace is ncountered. C+
encount.
is to the
When the
function
and control
returns
In fact, C++ has
1as added many ne
added .
main ()
/ m a i nprogram statements
This is perfectly valid because the main() in C does not return any value.
In C++, the main() returns a value of type int to the operating system. C++, therefore, explicitly defines main) as
matching one of the following prototypes
int main ();
int main (int char
argc, *
argv [] );
The functions that have a return value should use the return statement for
is, therefore, defined as follows: termination. The main() function in C+
int main ()
return 0;
problem. The explicit use ofvalue of zero means the value) to determine if there
is any
normal
a program
return(0) statement will ran
probiem
successfully,
indicate that the while a nonzero value
means u
program was successfully
executcd
77
Functions in C
4.3 FUNCTION PROTOTYPING
The argument-list contains the types and names of arguments that must be passed to the function.
Example
Eloat volume (int x, Eloat y, £loat z)
Note that each argument variable must be declared independently inside the parentheses. That is. a combined
declaration like
In a function declaration. the names of the arguments are dummy variables and therefore. they are optional. That is.
the form
Example:
loat ame i n t a, float b, flcat
float v = a*b*C;
78
Programmingwith C
Oblect-Oriented
as follows:
be invoked in a program
volume(0 can
The function cal1
Function
volume (b1, wl, h1); //
cubel
'r
=
int main ()
The above un-expected output is because of the heterogeneous types of argument present in the list. The call va_arg
returns a 4-byte sequence from the list, as we have specified the type of the expected
argument to be an integer. The
compiler does not perform the type checking. Thus, such functions should be used with extreme caution.
can only work on the copies of values. This mechanism is fine if the function does not need to alter the values of the
gInal variables in the calling program. But, there may arise situations where we would like to ehange the values of
artiables in the calling progrum. For example, in bubble sort, we compare two adjacent elements in the list and
rchange their values if the first element is greater than the second. If a function is used for bubblesort then it should
e able to alter the values of variables in the calling function, which is not possible if the call-by-value method is used
rovision of the reference variables in C++ permits us to pass parameters to the funetions by reterence. When we
arguments by reference, the "formal' arguments in the called function become aliaves it isthe 'actual'work
ASscallin arguments
to in
b t
Now, if m and n are two integer variables, then the function call
Swap (m, n
80 with C
Programming
Object Oriented
their aliases (reference
variables) a and b. Reference variablesariables have been
and using indirection followe.
will exchange
the values of m n
this is accomplished using
pointers and as
S
traditional C,
discussed in detail
in Chapter 3. In
Function
definition */
int *b)/*
*a,
void swapl (1nt
This approach is also acceptable in C++ Note that the call-by-reference method is neater in its approach.
if (x > y)
return x;
else
return yi
*
81
One solution to . this problem is to use macro
definitions,
Functionsin C
The major drawback with macros popularly known as macros.
really functions and Preprocessor
is that
popular
they are not macros are
does not occur during compilation. therefore, the
checking usual error
function body
Example:
inline double cube (double a)
return (a*a*a);
#include <iostream>
return (x*y) ;
return (p/g);
int main ()
float a = 12.345;
float b = 9.82;
return 0;
C++ allows us
to call a function without
specifying all its arguments. In such cases, the funcetion asSIE when the
fied
to the paramcter which does not have a matching argument in the function call. Default values are specitic lets
ale
s the
and
function The compiler looks at the
is declared. prototype to see how many arguments a function
uses an vaBlues
default
program for possible default values. Here is an example of a prototype (ie., function declaration) with detau
83
mOunt (float principal, 1nt
Functions in C
period, Eloat
rate-0.15):
ofault value is specified in a manner
symacucally similar to
res default value of 0.i5 to the argument rate. A subsequent functionvariable initialization.
a
a The above prototvne
call like
amount (5000, 7)
value
//one argument missing
the value of 5000 to prineipal and t o
period and then lets the function
call
use default value of 0.15 for rate. The
value amount (5000, 5,0.12) //no missing argument
passes an explicit value of 0.12 to rate.
#include< iostream>
float amount;
tloat value (float p, int n, float r=0.15) ; / / p r o t o type
VOld p r i n t line (char ch='*', int len=40) ; //prototype
printline () //use default values to1 arguments
co
Out"\n Final Value "<amount<<" \n\n"
(Contd)
84 Programming with Ct+
Obiect-Oriented second argument
value for
//use d e f a u l t
printline ('= " )
return 0;
int n, float r)
value (£loat p,
float
while (year<=n)
return (sum);
========= =*
2. Default
parameters to the existing functions.
arguments can be used to combine similar functions into one.
pass argu
85
Functions in Ct
4.9 RECURSION
#include <iostream>
using name space std;
if (n == 0)
/base case
return 1;
return (n *
fact (n-1);//recursive function call
int main ()
int num;
cout
< "Enter a positive integer:
cin >> num;
Cout << "Factorial of " << num << is " << f a c t (num)
return 0;
(Contd.)
86
C
ect Oriented Programnning with
//base case
tower1 <e
cout < \nShift top disk from t ower "<
<tower2 ;
return;
innt main ()
int disk;
f (disk < 1)
cout <<
"\nThere are no disks to shift"
else
cout
<<"\nThere are "<< disk << disks in tower 1\
TOH(disk, '1' 2','3)
cout << \n\n" <<
di sk << disks in tower are shifted co
tOwe 2";
return O;
The output of
Program 4.4 would be:
Enter the number of disks:
There are 3 disks in
tower
Shift top disk from tower 1 to
Shift tower
top disk from tower 1 to
Shift tower
top disk from tower 2 to
Shift tower
top di sk from tower 1 to
Shift tower
top disk from tower 3
to tower
Shift top di sk from tower 3
to tower
Shift top di sk frorm tower 1 to
tower
3 disks in tower 1 are shifted to tOwer
87
Functions in Ct
4.10 FUNCTION OVERLOADING
overloading refers to the use of the same thing for different
fund
eo means that we can use the same function name to create purposes. C++ also permits overloading off
tasks. This is known as function polymorphism in OOP. functions that perform a
variety of different
h e concept of function
overloading, we can design a family of
:ferent argument lists. The function would
pertorm diferent operations
functions with one function name but with
The correct function to be invoked is determined by depending on the argument list in the function
checking the number and
type of the arguments but not on the
function type. For example, an overloaded add() function handles different
types of data as follows:
// Declarations
int add (int a, int b) ;
/1 prototype 1
int add (int a,
c); int b, int
/ prototype 2
double add (double x, double y) ;
double add (int p, double q) //prototype3
double add (double p, int q) / prototype 4
// prototype 5
// Function calls
Cout << add (5, 10) ;
// uses prototype
cout <<
add (15, 10. 0);
Cout << add (12.5, 7.5) //uses prOtotYpe
cout <<
add (5, 10, 15
//uses prototype
cout
//uses prototype 2
<<
add (0.75,5) /uses prototype 5
A function call first matches the
prototype having the same number and type of arguments and then calls the
appropriate function for execution. A best match must be
unique. The function selection involves the
following steps:
1. The
compiler first tries to find an exact match in which the types of actual arguments are the same, and use that
function.
. I f an exact match is not found, the compiler uses the integral promotions to the actual arguments, such as,
char to int
float to double
to find a match.
wen either ofthem fails, the compiler tries to use the built-in conversions (the implicit assignment conversions)
the actual arguments and then uses the function whose match is unique. If the conversion is possible to have
Lple matches, then the compiler will generate an error message. Suppose we use the following two functions:
square (10)
will cau either long or double, thereby creating an ambiguous
dn errorbecause int argument can be converted to
dation as to which version of square() should be used.
in combination with integral
Br steps fail, then the compiler will try the user-defined conversions
the
conversions are often used in handling
ns and built-in conversions to find a unique match. User-defined
c class objects.
88 Ct
Prooramming with
Object-Oriented
overloading.
illustrates function
Program 4.5
Function Overloading
Program 4.5
overloaded three times
() is
Function area
#include< iostream>
int main ()
Cout< "Calling the area () function for Comput ing the area ot a square
return (side*side) ;
The output of
Program 4.5 would be:
Calling the area() function for
(side = 5) 25 computing the area of a
square
Calling the area () function for
5, breadth 10) 50 comput ing the area of gth
a
rectangie
Calling the area () function for
(radius = 5.5) 94.99 comput ing the area of a circle
89
Functions in C
na of the functions should be dorne with caution.
we should not
overload unrelated functions
averloading for functions
reserve function overloadir that perform closely related tasks. and should
Sometimes,
used instead ofoverloading. This may reduce the number of functions to be defined. the default arguments be may
coaded functions are extensively used tor
handling class objects. They will be illustrated later
are discussed
in the next chapter. when the classes
ANSI
conventional C+* atd cmath in
math.h in
To use the must include
the header file
math library
orary functions.
functions, we
C++
l
Functions
Program 4.6 Use of Math
#include<iostream>
#include<iomanip>
# i n c lude <cmath>
int main ()
cout<<fixed<<setprecision (2
cout<<"sin (100) "<<sin ( 100.00) "\n";//Comput ing sine value
<<
return 0;
SUMMARY
Otis possible to reduce the size of program by calling and using functions at
different places in the program.
OIn Ct+ the main() returns a value of type int to the operating system. Since the return
keyword int in the main() header is optional. Most C++ compilers issue a
the type of functions is int by del
warning, if there is no return staterme
OFunction prototyping gives the compiler the details about the functions such as the and
OWhen a function is declared inline the compiler replaces the function call with the respective function code. rmally.
small size function is made as inline.
91
unctions in CH
n i l e r mav ianore the inline declaration it the function
the function as a normal function.
declaration is too long or too
complicated and hence compile
allows us to assign defaut
all afunction without specityingvalues
to tne
all is runction parameters when the function is declared.
arguments. Ihe defaults are In
always added from right to left. such a case s
C an argument to a function can be declared
as const,
argument. indicating that the function should not
modify the
CHAllowsfunction overloading. Ihat is, we can have more than
enmoiler matches the function call with the exact function code one function with the same name in our
by checking the number and program. The
OC++ Supports two new types of functions, namely friend type of the arguments.
functions and virtual functions.
Many mathematical computations can be carried out
using the library functions supported by the C++ standard
library.
KEY TERMS
actual arguments argument list bubble sort call by reference call by value called function
program calling statement cmath const
arguments declaration calling
values dummy variables ellipses statement| default arguments default
empty argument list exit value formal arguments friend functions function
call function definition function
functions macros main()
overloading| function polymorphism function prototype indirection inline inline
mathlibrary math.h
variable return by reference return statement overloading pointers polymorphism prototyping reference
return type return()| template| virtual functions
REVIEW QUESTIONS
Cognitive Domain
Restate the different styles of writing prototypes.
Point out errors,
if any, in the following function prototypes:
(a) float average(x.y);
(b) int
mul(int a,b);
(e)int display(.);
(d) void Vect(int? &V, int &
size
(evoid print(float data[ }, size =
20);
4.3
Indicate the most gnificant advantage in using references
instead of pointers.
declaration.
a function
parenthesis in
Express the
significance of an empty
4.7 to use this concept
relate with suitable
example when
Also
Restate function overloading.
4.8 conditions the compiler distinguishes
Under what
function overloading.
4.9 Express the ways toachieve functions having the same name?
between a setof overloaded
Affective Domain
statements:
Defend the correctness of the following
4.10
to the calling program.
(a) A function argument is a value returned by the function
arguments in the
value, the function works with the original
(b)When arguments are passed by
calling program. to a variable.
be assigned
(c) When a function returns a value, the entire function call can
int m = 1;
return(&m);
(b) double f
return (1);
int n 10;
return(n);
Legend
Precision Valuing/Responding/Organizing Applying Remembering Understanding s
93
Functions in C
DEBUGGING EXERCISES
4.1 Identify the error in the following program:
#include <iostream>
using namespace std;
int sub (int a=20, int b)
int result;
result = a - b;
return result;
int a 2
float b =2.5
int show (a)
float show (b)
return 0;
4.3
ldentify the error in the following program segment:
#include <iostream>
using name space stdji
int pi
int &
display 0
int main ()
display () =5;
cout << p
return 0;
int&display
return 2;
94 Ctt
Programmingwith
Object-Oriented
DRY-RUN EXERCISES
run?
when the following program is
4.1 What will happen
#include <iostreamn>
int r;
r=p+i
return r;
int main ()
42 What will happen when the following function is called with different values (positive and negative) for count?
if (count == 0)
cout<<Count;
else
cout <<count<<endl;
fun(--count)
return;
X+t
return (x);
95
Functions in C
int main ()
int a
fun(a)= a;
Cout << a << endl;
fun(a)= a+t
cout << a << endl;
return 0;
#include <iostream>
Using namespace std;
int main ()
PROGRAMMING EXERCISES
4.1 Write a function to read a matrix of size m x n from the keyboard.
4.2 Write a program to read a matrix of size mxn from the keyboard and display the same on the sereen using
functions.
4.3 Rewrite the program of Exercise 4.2 to make the row parameter of the matrix as a default argument. e l
4.4 The effect of a default argument can be alternatively achieved by overloading. Discuss with an example.
MULTIPLE-CHOICE QUESTIONS
(a) 4
declaration of function
1. Select the incorrect
(b) 40
(a) int sum (int x, float y)
(b) float sum (float x, int y) (c) 0
LEARNING OBJECTIVES
will be able to
After going through this chapter, you
t of class templates
□ Explain the concep d with class templates
D Discuss how multiple parameters are use
D Explain the concept of function templates . I
d with function temp ates
D Discuss how multiple parameters are use
D Determine how template functions are overloade~
D Describe how member template functions are defined
12.1 INTRODUCTION
Template is a concept which enables us to define generic classes and functions and thus provides support for ge11tnc
programming. Generic programming is an approach where generic types are used as parameters in algorithmssothii
they work for a variety of suitable data types and data structures.
A template can be used to create a family of classes or functions. For example, a class template for an arraycli-1
would enable us to create arrays of various data types such as int array and float array. Similarly, we can define 1 ,
template for a function, say mul(), that would help us create various versions of mul() for multiplying int, float ltd
double type values.
A template can be considered as a kind of macro. When an object of a specific type is defined for actual use. the
template definition for that class is substituted with the required data type. Since a template is defined with aparamtrtr
that would be replaced by a specified data type at the time of actual use of the class or function, the templates are som~~
called parameterized classes or functions.
l
lnt opc ~aLuTk(vcc tor &y )
{ II scalar product
j nt 8 Uffi 0;
for(int i - 0; i <size ; i++)
sum I·= this -> v[i) *
Y · V [i] ;
return s um;
l;
'fl • vector class can store an array of int numbers and perform the •
,c sea1ar product of two mt vectors as shown
1,e1ow:
int main()
Now, suppose we want to define a vector that can store an array of float values. We can do this by simply replacing
1he appropriale int declarations with float in the vector class. This means that we have to redefine the entire class all
oreragain.
Assume that we want to define ~ vector class with the data type as a parameter and then use this class to create a
l'ec1or of any data type instead of defining a new class every time. The template mechanism enables us to achieve this
I goal.
Asmentioned earlier, templates allow us to define generic classes. It is a simple process to create a generic class using
aicrnplate with an anonymous type. The general format of a class template is:
temp late< clas s T>
clas s classname
II · · ·· ·
II clas s member spec i' fica tion
I I i11i th anonymous type T
II wherever appr opri ate
II · ····
}i
T* Vi
II Type T vect or
int size ;
publ ic:
vect or (int ml
v = new T[si ze = m] i
for( int i=O; i <si ze; i++)
v [i) = 0;
vect or (T* a)
};
~-.p ''
cri:ill \; ' " < u,,.1he "Ynt ait fo r dcfin ini
f
4r\ ,,1-tje<.l r,( .1 1c rr?1
.1' c:
ub ) •, 1
1- n ,,mr
,·f\ 1 int:! ,.
I• •
t ·-' >- - - - - - - - ,r,➔ 1
1 P'·- -
------1
l',t 1;
1
' '
Of g a sp ec ifi.c cl
•
cr ca un
0ccss . as s fro m a c\a..,., te m pl at e i.., ca lle
·~pr IY w h n an in sta nt 1a t1 . d in 11 un 1ia t,r m 1hc
comp1kr '-"111 pe rfo rm
'fltl \v!>is on . . nteo a te m on t ak es plc.ce . It '"•
th er ef or e. adv1, c1ble
to ,•r e
pl at e. cr ea te and de'->u ; an or
1 ~1101 1ing1tl dt r .H) c .1.. "
t!{f~fl! ,oo"cr
1 · I and 12 2 ill us tra te th e us e of a vector cl as
. .
\2 .
3111 s t ty , tem pl ate for pe rfo
progr well as (loa pe ve ct or s. rm in g th e •,u l.ir pro
dc1c\ of m t t)p e
i1S
{ =ne w T ls iz e1 ;_
V .
' -Q ·i <S1. Z€ ; l.+
fo r( ::.. .nt-- 1. - ' +)
., l i 1 = o ;
)
ve c to r (T * a )
{
f o r ( 1.nt • - o ·i < si ze ;i + + )
l. - , .
vl i 1 == al1.1
}
T op er a t o r * (v ec t o r &y )
{
T s um = O ;
. t · i z e · 1. +.,.. )
fo r ( in i:-:.O ;ih< 5 , ,.,
" y .•f~r -• \>,•
l. s - > ,n 1.
su m + - c. •
re tu rn su m ;
)
v o id d is p la y (v o id )
{ . p
. .
fo :r (1.nr.. l -- 0 i i< Sl .Z - ,· i ++
" \
co ur ..< <Vrtl. 1< < ~" " ,
.
co ut .< <" \ n" '.
);
in t ma i n t )
If .
c::n.:.:<<"·12 == ,, ;
v2 . dis pla y (1 ;
!
I
I
ret urn O;
I
f
Program 12.2
T sum= O·,
for(int i=0 ; i <si ze;i++)
sum += this - > V [ i]
* Y-V[i] ;
return sum;
l; main ( l
illt
( float x[3) = {1.1,2. 2,3.3};
float y[3] = {4 . 4 ,5 .S, 6.6};
vector <float> vl;
vector <float > v2 ;
vl = x;
v2 = y ;
cout<<" vl = " ;
vl. display () ;
cout< <"v2 = ";
v2.disp lay ( );
cout<<" Vl X v2 = "< <Vl*v2 ;
return 0;
vl X v2 = 3 8 . 7'2 000 1
);
·I· , . with two generic data types.
'lle C ,ISS
. f ·1tclllP'l
Progrant 12.
3 de111onstrates. the use o ,
- • i, •
-----~
•
~
i OiJ& . I -
-
•
I Program 12,3 • . -
• tream>
#include <10s
I
std·
using namespace ,
Tl, c1ass T2 >
template<cla ss
class Test
{
Tl a;
T2 b;
public: T y)
Test(Tl X, 2
{
a== x ;
b == y;
}
void show()
b << "\n".'
cout <<a<< " and " <<
};
int main()
cout«"Insta ntiating the class template as tes tl with float
and int data types .. \n tes t l: ";
Test<float , int>test l(l. 23 , 123 );
test 1. s how() ;
return O;
namespace s td;
usil19
· i ate<class Tl=int, class T2 .
ternP ==lnt> //d
55 rest efault dta tyP
cla es specified a s i n t
( Tl a;
T2 b;
public : Test (Tl X, T2 y)
{
a= x;
b = y;
}
void show ()
{
cout< <a <<" and ,,
<<b<<"\n" .
} I
};
int mai n ()
(
Test <float,in t> testl(l _23 ,
123 ).
Test <int, char> test2 (100, 'W ' ) .
Test <> test3 ('a ' , 1 2 . 98 3 ) . //d ' .
. . ' ec 1 arat1on of class object
without types specifica tion
test 1. show () ;
test2.sho w ( ) ;
test3.sho w( ) ;
return 0;
T temp= x;
X = y;
r = temp;
This essentjaJly declares a set of overloaded functions, one for each type of data. We can invoke the
like any ordinary function. For example, we can apply the swap() function as follows: swap() fun~
This will generate a swap() function from the function template for each set of argum t t p
how a template function is defined and implemented. en ypes. rogram 12.5shows
f Program 12.5
#include <iostream>
Y = temp ;
(Contd.)
fu!l (inc m, inc n ,fl o at a,fl oat
b)
"oid
cou~ c c "m and n bef ore swa p:
,,
swap (m , nl ; << m << " ,, <<
cou c cc "m and n aft er swa p • ,, n << " \ n";
· cc m
<< " " cc n
<< " \ n";
cou c c c " a and b bef ore swa p·
.
,,
swap (a,b ) ; <<
a << " " cc
b cc " \ n ";
cou c c c "a a nd b aft er swa
p• ,,
. << a << " "
<< b cc " \ n" ;
....ain ( l
;.!lt ,..
retu rn 0 ;
Ttem p = v(j ];
v[j) = v(j -1] ;
v[j - 1] = tem p;
in c •m a in ()
{
0 ,2 0 };
{1 0 ,5 0 ,3 0 ,4
in t X [S ] = . 4 ,2 .2 );
y{ S J = {1 . l, 5 . 5 ,3 . J ,4
fl o a t lu e s
fu n c ti o n fo r in t v a
I I c a ll s te m
p la te t va lu e s
b u b b le (x ,S ); te fu n c ti o n fo r fl o a
p la
I I c a ll s te m
b u b b le (y , S J;
c o u t << "S o rt e d x -a rr a y : II •
I
fo r( in t i= O ; i < 5 ; i+ + )
c o u t << X ii ] Cc " II •
I
c o u t << e n d l;
n;
j
o rt e d Y -a rr a y :
c o u t << "S
fo r( in c J=
O ; J< S ; J+ + ) i
(ConJJ.I
cou t < < Y [ j ) < <
cou t << e ndl ;
11 ,,
=--------..,.,. 361
@•J 1 ;I, 'tl ::J
re t ur n O;
~
list as shown below: 'using a c
{
(Body of f unction)
}
n empIate functions
Program 12.8 illustrates the concept of usinuo two generic types i t
WMm
I
Program 12.8 r:I!_.~ ·
}
int mai n ()
{
cout<< "Call ing ' func t·
string type i on template with int and char acter
. par amete
d i spl ay (l 999 "EBG") rs
I . .
... \n"· I
} retur n O;
. , ,n, 11 1 17., X w1111ld Im:
1111 ol 11111 ·
• 1,c111111 , , , l ,, 1 , 1 , 11 'I , 1 • "
1 1 1 11 , .,, 1 I I, l I I
I I, I
1l I 11'1 ti f
, \,,. r " ' l •
(',I I I 1, 1 I 111 '!
1''
'} ') .
l.' I\I •
I
/J i' f,•J f • llrl ' I I c; , , ,
j ,iri t· l \11 11 I 1·11q , \,, t, ,,, \ I I , I I I I• "
11 I 11'1 -'H 'I 'I,, I ' "
I' I I .
(', I I '/ ~" fl, ' •
i7. 1" f1•l l •J lfl' I ••r t: • ..
ovERLOA D IN G O F TEM
PLATE FU NC TI O NS
1z,6 1•tu.111,·li<>
; II ,nay he ow rlo ad cd either 1,y lcrnp
c111P :1c • •olutiol\ is ac.:co1 1· I hte
~ l . ,g res , I'i111clH1
.
11p HI ,cd a i; lol , . 11K<>r
I lowH: 1,rdi • I .
11,,ry unct1<m Kof ii~ name. In i-.uc h ca<.,ei,. the
o'c,10:1<,1
1
.
r·'inary tu11 ct1<• 111 th,1•1 h,1
. .
s an exac.:t 111atc.:h ·,
C,11 un o u
1. 1 .
. ,p\'IIC fu11c11on thal co uld
cull ii \i,;O ' . •' •
h1; cr1;al\!d wit.h , . .
2, •
3. 'frY non 11 '.,10wrloa<li ng r1;solul1011 lo ordinary fun an \!XaC\ match.
. . . cti< . , d .
mi. ,m call the one that match
. . ,,cn
•rror is cratc<l ,r no match 1s lound ei-. .
~•' r, ns Program 12.9 shows how a . Note lin' t no au
r:,
. 1oma11. c con
versio .
\alC func tcmphlc funct' .
11 ' • ' um "'o · ns arc •PP\'1cd lo argument
,en1P ver loa ded with an explicit function s on the
\,l ~~ l;;\!1ir.ffiroJimffil ~~
-~---- -- - - - -
•
program 12,9
~ lud"' ,, io c Lr <: r1111 ..-
\
' UiO C - .
\ tti nc lud e ,.c nt r Hl' J..-
. g na me sp ac r_ ::; td;
usin
\ templa t e -.:clc:1s::: T,.,
vo id di s pl ay (T ;;.:)
I
\
co ut •• •o va rl oa d e d Te
/ /o vr:: rl oa d e d te m pl at
mpl a te Di sp la y 1 ,
e fu nc ti0 n di sp la i'
in t ma in ()
di sp la y( lO O );
di sp la y( 12 .3 4)
di sp la y( l0 0, 12 .3 4)
di sp la y ( 'C ')
re tu rn O;
9 be:
The output of Program 12- would
Ex pli cit dis pla y : lOO
ay l : 12 . 34
Over l oaded Temp l ate Di spl
Overl oad ed Te mp lat e Di
sp lay 2 : 10 0, 12 .3 4
lay 1 : C
Over loa de d Te mp lat e Di sp
dn t
l display(100) invokes the ordinary version of display() an o the tern
ll Note
The cal 'Plate,.
•e/'8 •
LATES
'<It j
12.7 MEMBER FUNCTION TEMP
were defined as in• 1.
we created a class template for vector, all the member functions Inewh1·
. ch Was notn
Wnen tha t the memb er f
out side the class as well. But remember unction 1,
We could have define d them s of the le!JJPIarecesl.~
typ e argum ent (to their template classes) and th ereior
c
e th ,.
the
themselves are parameterized by m: ese fun cr ec~l
ionsIll
e\
It takes the following general for
defined by the function templates. Us!~
as follows·
member functions are redefined
The vector class template and its ·
as s te mpl at e . . . . . ...
II Cl
templ at e< cla ss T>
cl as s ve cto r
{
T* v ;
i nt s i ze ·
publ :
ic '
ve cto r (in t m) ;
ve cto r( T* a ) ;
T op era t or *( ve cto r & y) ;
v = new T[ siz e = .
. _m
fo r(i nt i:: o-, l< l,
s1 ze • i ++ )
V [i] = O·I I
}
class T> ll#iUf&rt4;:&Jr 36s
1uq;,t.ffi
~c. 1 ~ce~
~ T
(
.. vector T* a) 't'
c::;'' .:: > ..
,:e
ccot
, for (int i= O; i<si ze; i++ )
t v[i) = a[i) ;
T a [size] ;
II automatic array initialization
I I ... ..
II .....
};
SUMMARY
0 C++ supports a mechanism known as template to implement the concept of generic programming.
0 Templates allows us to generate a family of classes or a family of functions to handle different data types.
0 Template classes and functions eliminate code duplication for different types and thus make the program development
easier and more manageable.
0 We can use multiple parameters in both the class templates and function templates.
11
, •
0
•
c:
lled a template class and the process of crear
t dfrom aclass te~plate ,~ created from a function template is called a
Aspecific class cr~a e s·milarly aspecrflc tune ,o P
te:~
alertip1a1e
ate funl'I: '
· t ntiatJon. 1
' d "ijon· ~
known as ins a . be overloade •
m late functions can .
0 Like other functions, te P defined as function templates using the parameters of
lass template must be the class
0 Member functions of a c . or derived data types as arguments templates. telllp~fe
arameters such basic .
0 We may also use nontype p
KEY TERMS t t· t I t I ·
. explicit function I unc ,on emp a e generic programmin .
bubble sort I class template I drs~lay() I meters I overloading I parameter I parameterized classe g I lnstanlia.
I template function I te~ 1 Paratneie~
1 member function template I multrp:et p~r~emplate class I template definition
functions I swapping I swap() I temp a e P1ate Parameter
I template specification I templates
REVIEW QUESTIO~-~S
Cognitive Domain
12.1 Rewrite about generic programming and its implementation in C++.
12.2 Explain with the help of an example the requirement of templates in programming.
12.3 A template can be considered as a kind of macro. Distinguish the difference between them.
12.4 Distinguish between overloaded functions and function templates.
12.5 Distinguish between the terms class template and template class.
12.6
A cl~ss (or function) template is known as a parameterized class (or function). Justify the correctness I,.~
of this statement.
12.7 Choose the definitions that are illegal.
•
(a) template<class T>
class city
{ .. .. .};
(b) template<class P, R, class S>
class city
{.... .}
(c) template<class T, typename S>
class city
{.. .. . };
tatc<class T, typcnamc S> 367
1cn1P
(ti' ( I ' ( I I
{ .. l,
.::ctass T, int sizc=IO>
ctass '·
1rl ( l . [, I 1 1
I .. l ;
.::ctass T = int, int size>
ill cIas,5
C ) , If,.; I 1 ,l
{..... l ;
the function template definitions th· t . .
choose a arc illegal
1: .~ template<class A, B> ·
(:I)
void luril /\, 11)
{..... };
thl template<class A, class A>
voj rl fun(/ \ , /\.)
( .... .};
(cl template<class A>
void lur1(/\, /\)
{..... ),
(d) template<class T, typename R>
T [un('I' , I')
{,.,.•}I
(c) template<class A>
A [u11(1nt ~A)
-------
Legend
Precision
{..... } ;
@ Valuing/Responding/Organizing
-
\)
1 ,
>♦
i Applying ~
- - - - - - - --- - -
V r: r)r . C I <.~
DEBUGGING E1,r_ ,\..,IJ ___)
irl 111111,,1111:Lli
il•X'l 1, ,,.i1 1'1lltl,lJ(li
Object Oflented ProgrommlM with c++
public:
rest (l
{ intNumber == O;
floatNumber == o.O;
int getNumbe r ()
return intNurnber;
float getNurnber ()
{
return floatNurnber;
};
i nt main()
Test objTestl;
objTestl .getNurnber();
return O;
m t2 = t2;
rn t l = tl;
cout << m_tl << <<
\I II
m_t 2 << endl;
person<int, float> ob·JPersonl(
person<fl oat, char> objp 1, 2. 345 )
o,· erson2(2 132
• I \ r; I ) ;
,e curn
l
·fy the error in the following progra
!deou m.
12.3 · t ream>
·nclude <10s
#l- . g namespace std ;
ll5J..n
iate <Class Tl, class T2 >
cernP MinMax(Tl tl, T2 t2)
1'1&
( return tl > t2? tl t2;
C0U t < < \\ i II
int main ()
Tl a;
T2 b;
public:
Test(Tl x, T2 y)
{
a=X;
t
b =Yi
voi d show()
' and " -:-: b<< ''\n " ;
cou t< ~a <<'
int ma in( )
123 );
Te st <fl oat , in t > tes tl{ l . 23,
.9 83) ;
Te st <fl oa t > t est 2 (9 . 99 ,12
tes tl. show {) ;
tes t2. show() ;
ret urn O;
DRY-RUN EXERCISES
g program is executed?
12.l What will happen when the followin
ifin clu de <io stre am >
int main {)
371
I .
Whal will happen when the following pro ra
,~) g rn is executed?.
ude - ')' r ~ r:.cn, •
~i n<: l
int main ()
I
\
fun (25 , 281
fun ( 2 5 / 2 8 • (j I I
_1:,1.,r;.!.ic:
,,.0,1,nttci Pro ram In wflh c1 ►
;, ,, i )
/\0 {x )
/\ ('I' y ) (x y;
vo i d cJii:p l ,lY()
{ X <·
<'ucll ;
('<JU L "- <
)
I;
i 11 L m,d n ()
I
A < "> obl;
A d n t> ob2 ;
A dn t > ob3 (35) ;
A <> ob4 (55.0) ;
obi . di splay ();
ob2 . di splay ();
ob3 .di sp l ay() ;
ob4.display ();
r e turn O;
PROGRAMMING EXERCISES
12.1 Write .'1 function template to find the minimum
and maximum values by passing non-type arguments to the
tcmplate. flw! E 11 j !
12.2 Write a class template to represent a generic vector. Include member functions to perform
the follow·mg tasks:
(a) To create the vector.
(b) To modify the value of a given element.
(c) To multiply by a scalar value.
(d) To display the vector in the form (10, 20, 30, ......). jiw!1E [ nJ
- - -I
Write a function template to perform linear search in an array. jJw! E [ e
Write a class template that shows the working of a calculator.
MULTIPLE-CHOICE QUESTIONS
1. Instantiation of template lakes place at 2. 'Using template complete source code hidingis
(a) run time
possible.'
(b) compile time
(a) Not really
(c) load time
(b) Pretty much
(d) link time
(c) Exactly
(d) Never
ropriate template? 7.
·s an app Choose the belong to
,vhich t template type temPa
plra
at meter that does not
e:
J 1ass non-
• 01) c ·onal template (a) type
b) funcllber functio
n template
( 111 em (b ) Pointer to ob
ject
(d O
f them
t o create c1ass (c) reference to pointer
l
al the correct sy nt ax ber
cdl (d) pointer to mem
Choose 8. mplate in C++:
J late? Keyword for using te
. telllP 01p<CJass P > (a) template
(o) te ( lass P,
class Q )
Q (b ) typename
temP c as s P, cl as s >
(b) template<cl (c) class
(cl late (class P ) . (d ) all of these
) tem P er 1s:
m et in
(d eo ft em plate pa
ra
tity that cannot be directly parameterized
9. En +:
in block C+
5. scopW•th l
)
(a ·u program en
ds (a) enumerators
(b) u (b ) constants
"thin class
) WI (c) templates
(c f these
) none o (d ) types
(d lated wrapped in
ternal classes are:
Re out template?
6. d 10. What is not correct ab
tion
(a) bin
(a ) generates a
family of classes/func
(b) rebind
(b) eliminate code
duplication
aded
(c ) late bind (c) Template func
tion cannot be overlo
(d) unbind {d) it can be cons
idered as macro