0% found this document useful (0 votes)
83 views367 pages

C++ Cs

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)
83 views367 pages

C++ Cs

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/ 367

4 Functions in C+

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

void show ) ; Function declarati on */


main ()

/* Function call *7
show()

void show () /* Function de f init ion */

Funct ion body


76 with C function body. Thc other st
statement in
Programming
statement in the
to the first
Obyect-Oriented

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 .

then executed of C++ programs.


body are blocks
the function
Functions
to be the building
continue
Like C++ operators,
a C++ function can be
overloaded t
ouodt

is no exception. reliable and


flexible.
these modifications are a med a
to it. Most of
them more
functions to
make
features to on the arguments passed
different tasks
depending
make it perform facilities.
requirements of object-oriented
meeting the features that are added to C++ functions and
and their
new
discuss the various
In this chapter, we shall briefly
implementation.

4.2 THE MAIN FUNCTION


function which is the starting point for the execution of a program. The
C does not specify any return type for the main()
definition of main() would look like this:

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;

Since the return


type of functions is int
compilers will generate an error or by default, the keyword int in the main()
Function should
warning if there is no return statement. header is
Turbo C++ issues the
optional. Mo st C+
return a
value warning
and then
proceeds to compile the
program. It is a
good
Many
operating systems test return programming practice to actually return
convenion that an exit
is the value (called exit a value irom ain.

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

Eunction protoryping major improvements added to C++ functions.


is one of the
interface to the ceniler bv giving details such the number and of
as
The prototype describes the
function
type
arguments and the type of return values. With
function rototyping.
a template is alw
lways used when declaring and
s the template to ensure that proper arguments are defining function. When a function is called. the
a
compileruses
passed. and the return value is treated
violation in
matchi the arguments or the return
types will be caught by the correctly. Any
Thase checks and
controls did not exist in the compiler at the time of
conventional C functions. compilation itself
Dmember. C also prototyping. But it was introduced first in C++ by
uses
.

the ANSI C committee to adopt it. However. there is a


Stroustrup and the success of this feature
insp major difference in prototyping between C and
hile C++ makes the prototy ping essential. ANSI C makes it optional.
While C++
perhaps. to preserve the compatibility with
classic C.

Function prototype is a declaration statement in the


calling program and is of the follow ing form:
type f u n c t i o n - name (arguma
1

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

Eloat volume (int x, £loat y, z)


is illegal.

In a function declaration. the names of the arguments are dummy variables and therefore. they are optional. That is.
the form

float vol ume (int, float, float);


checks for the type of arguments when the
acceptable at the place of declaration. At this stage. the compiler only
function is called.
either include or exclude the variable names in the argument list prototypes. The variable names
of
general, we can
are used. they don't
have to match the names used in
in th
prototype just act as placeholders and. therefore. if names
the function
call or function definition.
must be reterenced inside the tunction.
required because the arguments
C unction definition, names are

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
=

which specify the dimensions of cuhel


float
the actual parameters
known as ty
declared in the prototype. Remember, the
hl
The variable bl, w1,
and are

should match with the types


the ember, calling
have been declared earlier)
(which n a m e s in the argument
list.
statement
include
should not type
in the following example:
empty argument list,
as
also declare a function with an
We can

void display ();


It is identical to the statement
In C++, this means that the function does not pass any parameters.

void display (void);


However, in C, an empty parentheses implies any number of arguments. That is, we have foregone prototyping
the prototype shown below:
'open' parameter list by the use of ellipses in
as
C++ function can also have an

void do_something list_of_arguments,


Functions using ellipses must have one or more declared arguments provided in the list_of_arguments. Use of sa
functions which support variable number of arguments would require the inclusion of the header file "cstdarg".Te
following program demonstrates the use of a function with a variable argument list:

#include <iostre am>


#include <cstdarg>

using namespace std;


int findmax imum (int count,

int max, value;


va_list list; //declare variable argument list
va_start (1ist, count); //start accessing variable list
max =va_arg (1ist, int); / extract the first element of l i s t
for (int arg 1; count;
arg ++arg)
=
<

value= va_arg (list, int);//extract each successive element fro*


if (max < value)
max = value

va_end (list) //end the access of the variable argument


return max

int main ()

cout << findmaximum (5, 14, 15, 12, 13,


cout << findmaximum (3, 10, 11, 10)<< endl
return 1;
12)<< endl;
79
The output ot this Drogram will be: Functions.ln C
15
12

ra0ram the elements from the variaDIe nst are accessed


through "va_arg (lis1, int)". It
e d argument (in this case- ing. iowever, note that the compiler has no way
specifies the type of the
their type. Let
consider the following:
us of checking the list of parameters for
1nt main (

cout << findmaximum (5, 14.0, 15, "Hello", 13, 10)


cout << findmaximum (3, 10, 3.5, 12) << endl; ndl
return 1

The above function calls will pass the


compiler's test and will not
give any errors. However, when run, it will give the
following output:
1076625408
1074528256

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.

4.4 CALL BY REFERENCE


In traditional C,
function call passes arguments
a value. The by called function
creates a new set of variables and copies
the values of arguments into them. The function does not have access to the actual variables in the calling program and

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

unction. This that when the function is its


working with own áctually
arguments, ing the on
g means
Original data. Consider the
following function:
VOld reterence vat lables
swap (int &a, int &b) // a and b are

int t a // Dynamic i n t i a l 1 2 a t iOn


a b

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

int t value at address a to t */


a /* assign the
b into a */
*a *b /* put the value a t
t /*put the value a t t into b */

This function can be called as follows:

swapl(&x, &y) /* call by passing */7


/*addresses of variables */

This approach is also acceptable in C++ Note that the call-by-reference method is neater in its approach.

4.5 RETURN BY REFERENCE


A function can also return a reference. Consider the following function:

int &max (int &x, int &y)

if (x > y)
return x;
else
return yi

Since the return type of max() is int &, the


function returns reference to x or y (and not the
call such as max(a, b) will values). Then a functot
yield reference to either a or b depending on their values. This means that this
a
can appear on the left-hand side function cal
of an assignment statement. That
is, the statement
max (a, b) =-1
is legal and assigns -1 to a if it is larger, otherwise-1 to b.

A function should not be made to return


Note the reference of
function). This would result in a warning from the an auto variable (scope within ne
compiler.

4.6 INLINE FUNCTIONS


One of the
objectives of using functions in a is to
function is likely to be called many times. program save some
memory space, which becomes
a series of instructions for tasks such as However, every time a function is
called, it takes a lot
appreciad tit
returning to the jumping to the function, saving of extra tine a
calling function. When a function is registers. pushing arguments into
stack.

such overheads. small, a substantial t


percentage of execution time may De
Spent.

*
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

adifferent solution to this problem. lo eliminate the


line function. An inline function is cost of calls to small
functions, C++ propose
featurecalled function that is
a
s the function call with the corresponding function expanded in line when it is invoked.
compiler code That is, the
inline functions
are defined as follows: (something similar to macros
expansion). The
inline functi on -header

function body

Example:
inline double cube (double a)

return (a*a*a);

The above inline function can be invoked by statements like


c =
cube (3.0)
d =cube (2.5+1.5)
On the execution of these
statements, the values of c andd will be 27 and
64, respectively. If the arguments are
expressions such as 2.5 + 1.5, the function passes the value of the
far superior to macros. expression, 4 in this case. This makes the inline feature

It is easy to make a function


inline. All we need to do is to
inline functions must be defined prefix the keyword inline to the function definition. All
before they are called.
We should exercise care before
making a function inline. The speed benefits of inline functions diminish as the
Tunction grows in size. At some point the overhead of the function call becomes small compared to the execution of the
unction, and the benefits of inline functions
may be lost. In such cases, the use of normal functions will be more
dnngtul. Usually, the functions are made inline when they are small enough to be defined in one or two lines.
Example:
1nline double cube (double a)
{return (a*a*a) ;
tr rthat the inline keyword merely sends a request, not a command, to the compiler. The compiler may ignore
estif the function definition is too long or too complicated and compile the function as a normal function.
Some of the situations
O where inline expansion may
not work are:
1. For
functions returning values, if a loop., a switch, a goto exists. or
2. For
3.
functions not returning values, if a return statement exists.
If functions contain static variables.
4.Ifinline functions are
recursive.
82
Programming with C
Obiect-Oriented

makes program run


a
faster because the Overhead of a function function call and
Inline expansion to take up more memory beca
return is eliminated.
However, it makes the program because the
that define the inline
function are reproduced at each point where the func
function is
Note statements
called. So, a trade-off becomes necessary

illustrates the use of inline functions.


Program 4.1

Program 4.1 Inline Functions

#include <iostream>

using namespace std;

inline float mul (float x, float y

return (x*y) ;

inline double div (double p, double g)

return (p/g);

int main ()

float a = 12.345;

float b = 9.82;

cout << mul (a, b) << "\n";


cout<< div (a,b) <e \n";

return 0;

The output of Program 4.1 would be:


LIMITATION
the
121.228 An inline function can increase
it ma
1.25713 function size so much that
not fit in the cache.

4.7 DEFAULT ARGUMENTS


a d e f a u l tv a l

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.

A default argument is checked for type


at the time of
declaration and evaluated at the time of call.
noint to note isthat only the trailing One important
arguments can have default values and
therefore
to left. We cannot provide a default value to a particular we must add defaults from
right
of function declaration with default values are:
argument in the middle of an
argument list. Some examples

int mul (int i, intj=5, int k=10); // legal


int mul (int i=5, int j);
int mul (int // illegal
i=0, int j, int k=10)
int mul (int
; // i1legal
i =2, int j=5, int k=10) ; // legal
Default arguments useful in situations where some
are
interest may remain the same for all customers for a
arguments always have the same value. For instance, bank
the programmers. A function can be written with
particular period of deposit. It also provides a greater flexibility to
more parameters than are
required for its most common application.
Using default arguments, a programmer can use only those that
arguments are
meaningful to a particular situation.
Program 4.2 illustrates the use of default arguments.

Program 4.2 Default Arguments

#include< iostream>

using namespace std;


int main ()

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

amount //default for 3rd argument


value (5000.00,5);
=

Outee "\n Final Value "<<amount<< " \n\n


=

Ount = value (10000.00,5, 0.30) ; //pass a l l arguments explicitiy

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

int year =l;


float sum = P

while (year<=n)

sum = sum* (1+r) ;


year = year+1;

return (sum);

void printline (char ch, int 1en)

for (int i=1;i<=len; i++)


printf ("%c" ,ch);
printf ("\n") ;

The output of Program 4.2 would be:

**** **** **** ************


********
Final Value = 10056.8
Final Value 37129.3 =

========= =*

Advantages of providing the default arguments are:


1. We default arguments to add new
can use

2. Default
parameters to the existing functions.
arguments can be used to combine similar functions into one.

4.8 const ARGUMENTS


In C++, an
argument to a function be
can declared as const as shown below.
int
int
strlen (const char *p);
length (const string &s);
The qualifier const tells the
an error when this condition is compiler that the function should not tenerate

violated. This type modify the argument.


arg The compiler will ge
or pointers. of declaration is significant only when we
referenet

pass argu
85
Functions in Ct
4.9 RECURSION

tuation where a function calls itselt, 1.e., one


Recursiouin of the statements in the function
thesame functioniin which it is present. It may sound like an
infinite looping condition but definition makes acall to
te the program control out of the loop, a recursive function
just as a loop has a
conditional
ontrol from the current instance of the function to call back to thealso possesses base case which returns
a
the
progra

actorial of a number, the base case


calls, to compute the fact calling function. For example, in a series of
recursive
would be a situation where
ilted. Let us consider a few examples (FTOgrams 4.5 and 44) to understand how factorial of 0 is to be
the recursive approach works.

Program 4.3 Calculating Factorial of a Number

#include <iostream>
using name space std;

long fact (int n)

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;

The output of Program 4.3 would be:


Bnter a positive integer: 10
Pactorial of 10 is 3628800

Program 4.4 Solving Tower of Hanoi Problem


#include <iostream>
using namespace std;
char tower3)
void OH(int d, char tower1, char tower2,

(Contd.)
86
C
ect Oriented Programnning with

//base case

tower1 <e
cout < \nShift top disk from t ower "<

<tower2 ;
return;

TOH (d-1, towerl , tower3, tower2);//recursive functior


cout << "\nShift top disk f rom tower "<< towerl <e tOWE
<tower2;
TOH (d-1, tower3 , tower2 , functior call
tower1)//recursive

innt main ()

int disk;

Cout < "Enter the number of disks: "


cin >> 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:

long square (1ong n)


double square (double x)
A function
call such as

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>

//Declarat ion of Funct ion Prototypes


int area (int);
int area (int, int);
float area (float) ;

int main ()

Cout< "Calling the area () function for Comput ing the area ot a square

(side - 5) "<<area(5)<<" \n";


cout<< "Calling the area () function for comput ing the area of a
rectangle (length - 5, breadth = 10) < < a r e a (5, 10) <<" \n" ;
cout<< "Calling the area () function for comput ing the area of a cicle
(radius = 5.5) -"<<area (5.5);
return 0;

int area (int side) //Area of square

return (side*side) ;

int area (int length, int breadth) //Area of rectangle


return (length*breadth);

float area (Eloat radius)


//Area of circle
return (3.14*radius*radius);

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

4.11 FRIEND AND VIRTUAL FUNCTIONS


C introduces two new types of functions, namely. friend function and
virtual function. They are
to handle some specific tasks related to class objects. Therefore, discussions on basically introduced
these functions have been reserved until
after the class objects are discussed. The friend functions are
discussed in Sec. 5.15 of the next
functions in Sec. 9.5 of Chapter 9. chapter and vinual

4.12 MATH LIBRARY FUNCTIONS


The standard C++ supports many math functions that be used for
can
performing certain commonly used caleulations
Most frequently used math library functions are summarized in Table 4.1.

Table 4.1 Commonly used math library functions


Function Purpose
ceil(x) Rounds x to the smallest integer not less than x ceil(8.1) = 9.0 and ceil-8.8) = -8.0

cos(x) Trigonometric cosine of x (x in radians)


exp(x) Exponential function e
fabs(x) Absolute value of x.

If x>0 then abs(x) iss x

Ifx=0 then abs(x) is 0.0

If x<0 then abs(x) is -x


Rounds x to the largest integer not greater than x floor(8.2) = 8.0 and floor(-S.8)= -90
floor(x)
log(x) Natural logarithm of x(base e)
log10(x) Logarithm of x(base 10)
pow(x.y) x raised to power y(x*)
sin(x) Trigonometric sine of x (x in radians)
sqrt(x) Square root of x
tan(x) Trigonometric tangent of x (x
in radians)
double
functions retum the data type
Note e argument variables x and y are of type double
and all the

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

rogram 4.6 demonstrates the use of.math functions


90
Programming with Ctt
Object Oriented

Functions
Program 4.6 Use of Math
#include<iostream>

#include<iomanip>
# i n c lude <cmath>

using namespace std;

int main ()

cout<<fixed<<setprecision (2
cout<<"sin (100) "<<sin ( 100.00) "\n";//Comput ing sine value
<<

cout<<"cos (100) "<<COS (100.00) <<"\n";//Comput i ng cosine value


cout<<"tan (100) ="<<tan (100.00)<<\n"; Comput ing tangent value

cout<< "7 to the power of 6 "< <pow(7.0,6. 0) <\n"; //Comput i ng


power of one value raised to the other
cout<elog10 (10) = "<<log10(10.00)<"\n" /Conputing log to
the base of 10 value
cout<< sqrt (2) ="<< sqrt (2.00) <<"\n"; /Computing the
square root of a value

return 0;

The output of Program 4.6 would be:

sin (100) =-0.51


cos (100) = 0.86
tan (100) = -0.59
7 to the power of 6 117649.00
log10 (10) = 1.00
sqrt (2) = 1.41

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

the type of return values. number and types of argumenis


OReference variables in C++ permit us to pass parameters to the functions by reference. A function can also reeturn a
reference to a variable.

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.

4.4 Predict when a function is to be made inline with relevant justification.

4.5 Distinguish between macro.


an inline function and a preprocessor
4.6
Relate
elate to
to the
t need of using default arguments in a function.
92 Programming with Ct
Object-Oriented

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

(d) A function can return a by reference.


value
in the calling program
(e) When an argument is passed by reference, a temporary variable is created
to hold the argument value.
(f) It is not necessary to specify the variable name in the function prototype.
4.11 Confirm the main advantage of passing arguments by reference.

4.12 Synthesize the following function definitions:


(a) int E(

int m = 1;

return(&m);

(b) double f

return (1);

(c) int & f()

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 main (){


int a = 100;
int b = 200;
int result;
result = Sub (b) ;
cout << "value 1 : << result
result = sub (a) ;
cout<< " value 2 " << result;
return 0;

4.2 Identify the error in the following program segment:


int main ()

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>

using namespace std;


int add (int p, int q)

int r;
r=p+i
return r;

int main ()

int x=7, y=5, Z


z = add (7,2):
cout << "Result 1: -" < < z << \n';
cout << "Result 2: - " << z +add ( 7 ,8 ) <<\n;

cout << "Result 3: - <eadd (x,y) <<


\n
z= 4 + add (9,y):
cout << "Result 4: - << z << '\n'

42 What will happen when the following function is called with different values (positive and negative) for count?

void fun ( int count)

if (count == 0)

cout<<Count;
else

cout <<count<<endl;
fun(--count)
return;

4.3 What will happen when the following program is run?


#include <iostream>
using namespace std;
int &fun (int &);

int & fun (int & x)

X+t

return (x);
95
Functions in C
int main ()

int a

fun(a)= a;
Cout << a << endl;

fun (a) = ++a;

cout << a << endl;

fun(a)= a+t
cout << a << endl;

return 0;

44 What will happen when the following program is run?

#include <iostream>
Using namespace std;
int main ()

cout << "Hello" <<


endl1
main()
return 1;

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.

4.5 Write a macro that obtains the largest of three numbers.


4.6 Redo Exercise 4.5 using inline function. Test the function using a main program.

4.7 The function takes a double value form and int


number to a power n.
.write a function power() to raise a m
calculate
vaiue 1or n, and returns the result correctly. Use a default
value of 2 for n to make the function to
a main that gets
the values of m andn from the user to test the
uares when this argument is omitted. Write
function. int value for m. Both the
rite a function that performs the same operation as that of Exercise 4.7 but takes an
functions. Use the concept of function
Write a main that calls both the
CEons should have the same name.

overloading. triangle and a circle by overloading the area()


the area of a
to compute
_program
function.
96
Programming with C
Object-Oriented

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

(c) int sum (int x, y) (d) 1


(d) int sum (int, float) What is about direct and indirect
true
recursion
2. int & super() (a) Function calls itself and function
call
return 2: ) What will this function return? another function to call calling function
(a) 2 (b)
Function calls another function and
functio
b) 0 call calling function
(c) error (e) Function calls itself in both
(d) 1 (d) Function calls calling function in both
3. Inline function works under this situation. 7. Choose the correct statement:
(a) if function had a
loop, switch and goto exists (a) Non-tailed recursion is better
than tailed
(b) if function contains static (b) Tailed recursion is
variable better than non-tailed
(c)iffunction is recursive (c) In non-tailed recursive call is last
statement
(d) None of these (d)
Linker optimizes in tail recursion
4. float FD (float 8.
principle, int time=5, float rate) Function that be
overloaded:
can
amount =
FD(2500.50, 7.25) (a) functions with
different return type
Which argument is default in (b) functions
the above? having member function static
(a) (c) parameter declaration different by const
b) 2nd (d) same name but
different parameters
(e) 3rd
The compiler may ignore inline declaration due
(d) none which reason?
5.
Compute the output of the (a) too long
following:
#include <iostream> (b) too small
using namespace std; (c) same as normal
inline int (d) due to no
large (int p, int q) parameter
zeturn (p>q) ? 10.
What is the maximum singe
int main() pq function?
no. of
arguments in a
cout << (a) 127
< "larger of two is: "
large (4,40) <<
"\n";
(b) 128
return 0; (c) 253
(d) 256
Templates

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.

12.2 CLASS TEMPLATES


Consider a vector class defined as follows:
class vector
(
int *v;
I 11 1 JI I i', I ' i
piitdl c· :
v , •r· l Il l ( i ril II\)
II r:rcr.1Lc 1
• c n1111 v ector
V I ll'W j 11 l I 11 j '/.t,
1111 ;
f0 1 ( i Ill O; i , ui_zp . .
~ I l H)
VI i I 0;
l
Vl!C' \ Or(i11l k ,1)
II C
reate a vector from
an array
r Cl r ( i Ill O; L<size I• i++)
VI j I <.1 [j];

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

int x (3) = { 1, 2, 3};


int y [ 3) = {4,5,6};
ve c t or vl(3);
II Creates a nul l vector of 3 in t egers
vector v2(3) ;
vl = x ; II Creates vl f r om the array x
v2 = y ;
i nt R = vl * v2;
cout < < " R = " << R;
ret u r n O;

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

h below illustrates the syntax of a template:


The template definition of vector class s own
temp late<c l ass T>
clas s vect or

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)

for (int i= O; i<si ze; i ++)


v[i) = a[ i) ;

T oper at or* (vec tor &y)


{
T sum = O;
for( int i =O; i <si ze; i++)
sum+ = this -> v [i ) * y . v [i ];
retu rn sum;

};

Note The class template defilition is very similar to an ordinary


class defilition except the ptefK
templafe<class T> and the use of type T. This prefix tells
the compiler that we are going m
declare a template and use T as a type name in the decla
ration. Thus, vector has become 8
parameterized class with the type T as its parameter. T may
be substituted by any data type
including the user-defined types. Now, we can create vecto
rs for holding different data types.
Example:
vect or <int > vl(lO );
II 10 elem ent int vect or
vect or <flo at> v2(2 5);
II 25 elem ent floa t vect or

INote The type Tmay represent a class name as well. Example:


vect or <complex> v3(5 );
II vect or of 5 complex numbets
I
~
.
,c} fro m a ca !..!. te m pl at e i!- ca lle d a te mn fu te

~-.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

,,,,., nt 12.1 ~ © !@ k m ~-~


progra ~ -~
~ ~-~
- _ _ _ __; __ _; _. ... ;.:
... .~ .;. ... ... ;~ ~=
\ de 'Q st te am ;,
.:: l.
,1nclu
, .
nam e s p ac e s ta ;
usin9
~ · ze = 3 ;
cons c. .::,l. .:: cl as s T
1a t e ;,
tetllP ec to r
cl as s "
l T* v; I I ty pe -: ·;e c: '.n
publ ic : v ec to r ( )

{ =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 .

ccu : << "·11 = ,


-1 1.d isp l ay ' ) ;

c::n.:.:<<"·12 == ,, ;

v2 . dis pla y (1 ;
!
I

I
ret urn O;
I

The output of the Program 12.1 would be:


vl = 1 2 3
v2 = 4 5 6
v l X v2 32

f
Program 12.2

#in clu de <i ostr eam >

usi ng namesp ace std ;


con st siz e= 3;
tem pla te <cl ass T>
cla ss vec tor
{
T* v; II typ e T vec ccr
pub lic:
vec tor( )
{
v = new T[s iz" '].
for (in t i=O ;i;s ize ·i+ +)
v[i ] = O·I '

vec cor (T* a )


{
for (in t. i-o • .
- ;1 <s1 ze; i ++)
vfi ] = afi ] ;

T ope rat or* (ve ct or &y)


355

T sum= O·,
for(int i=0 ; i <si ze;i++)
sum += this - > V [ i]
* Y-V[i] ;
return sum;

~oid display (void)


{
for (int i =0 ;i <si ze ;i++)
COUt<<V[ i] <<"\t" ;
cout<< " \ n";

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;

Theoutput of the Program 12.2 would be:


vl = 1.1 2 .2 3. 3
v2 = 4 . 4 5 .5 6 .6

vl X v2 = 3 8 . 7'2 000 1

12.3 CLASS TEMPLATES WITH MULTIPLE PARAMETERS


We can use more than one generic data type in a class template. They are declared as a comma-separated list within the
template specification as shown below:

t emplate< class Tl, c lass T2 , ...>


class classnam e
(

(Body of the class)

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

cout«"Insta ntiating the class template as tes t2 with int


and char data types . . \ntest2 : " ;
Test<int,cha r>test2(100, 'W ');
test2.show() ;

return O;

The output of Program 12.3 would be:


Instantiatin g the cl ass template as testl with flo a t and int data types ..
testl: 1 .23 and 123
Instantiatin g the class template as test2 with i nt and c har data types.·
test2: 100 and W
. .
Just as we specify default values for functmn arguments, we may also specify default types for the templatecla.li
data types. Program 12.4 modifies Program 12.3 to demonstrate default type specification:
raf1'112.4
pro9
l
~
P"
. ..,clU
e <iost ream>

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;

The output of Program 12.4 would be:


1. 23 and 123
100 and W
97 and 12
The above program declares test3 object without any type specification, thus the default data type for Tl and T2 is
considered as int. The parameter values passed by test3 are type casted to int and displayed as output.

12.4 FUNCTION TEMPLATES


Like class templates, we can also define function templates that could be used to create a family of functions with
different argument types. The general format of a function template is:
t ll/1 , ' ( i 1111
h I t 1J ( ) i ,, ' f
h',I1, • ? t '\ t •r· • iJ11ll\1ll
r r l J,I
. (
t
'

. .· ihr ch·tl of the dass template except that we are defin•


Tht' funr1 il,n 1t·mpla1e sy111:tx ,s l-11ll , 10 • . . . ing func .
. , . ·tm 'terr as nmi when necessary 111 the function body and . . honsin
dasst'S. We mus1 use the lt'lllPI,lit: p,tr, c . in Its argullle s1_Cad~
0
• . d ·cl·ws . swllp{) function template that will swap two values of a gi Ven type f 111s1,
Tht' tl,lkm'lflg cxamp1c t • t , •1 - 0
data
template.::class T> •
v01d ~wap(T,x, T&y)

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~

void flint m,int n,float a,float b)

·swap(m,n); I I .,-,.,,ap t 1110 in teger values


swap (a, b l ; I I s 111ap t1110 float val ues
II

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>

using namespace std;

templa te <class T>


void swap(T &x , T &y)
{
T temp= x ;
X = y;

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 ,..

fun (l0 0 ,2 00 ,11 .22 ,33 .44 );

retu rn 0 ;

of Prooram 12.5 would be:


"fbe output e
n bef ore s wap : 100 200
rn and
_ d n aft er swa p: 200 100
rn c.n
b bef ore swa p: 11. 22 33 . 439 999
a and
d b aft er s wap : 33.4 399 99 11.2 2
a an
Another function often used is sort () for sorting
arrays of various types such as int and double.
ws a function template for bubble sort: The following
b
01DPle s o •
tem plat e<c lass T>
bubb le (T v [] ' int n )
{
for ( int i=O ; icn -1; i++ )
for ( int j=n -1; icj ; j - -)
if (v[ j] < v[j - 1])
{
T tem p = v [ j ] ;
v[j ] = v[j -1 ) ;
v[j -1] = tem p;

Note that the swapping statements

Ttem p = v(j ];
v[j) = v(j -1] ;
v[j - 1] = tem p;

maybe replaced by the statement

swa p(v[ j] ,v[ j - 1]) ;

•here swap() has been defined as a function temp


late.
36 0
. returns a value.
here a func tion
rL -- -- - her exam ple w
Herc: 1·s anot
l a te < c la s BT>
T y)
te m p
T m ax (T x ,
{ X >Y
? x :y ;
re tu rn
gram 12. d emon!>trare\ lh
m pl ate fu n ct ion. Pro am 126.7 sh
. c al le d a te
algorithm. P ro gr . ow, ••011~ '>••.,.,,,
. temIplate is
ting the bu bb le so rt ,,
} a fu nc twn. emen
le
oene. ra md fr om fo nm p
. . nested. form
tw oAtemfupl e nfu•ncr,ons
ncatr,o
nctions.
. n o f temp/ale fu
. at w
o f ap pl ic
m ~ • f t if @ ~
m 1 2 .6 I D ! [ ; f t f @ ~ r ! I f ih
[ Progra
st re a m >
# in c lu d e < io
p ac e s td ;
u si n g n am es
ss T >
te m p la te < c la n)
(T a [] , in t
v o id b u b b le
{ +~
; i < n -1 ; i+
fo r (i n t i= O -)
-l ; i < j ; J -
fo r (i n t j= n
[ j- l] )
i f (a [ j] < a
{ n c ti o n
[j - l 1 ) ; te m p la te fu
sw ap ( a [j 1 , a // c a ll s
}
}
ss X >
te m p la te < c la
& a, Y. & b)
v o id s~•1 ap (X
{
X te m p = a ;
a = b;
b = te m 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;

~ f program 12.6 would be:


ffteoutpU
d x - arra y: 10 20 30 40 50
sort ed y- arra y: 1.1 2 . 2 3.3
4 . 4 s .s
sort e

Ip,og,am 12.1 la m ~ 0'}~

~ lude <io stre am>


7
#l nam espa ce std ;
usin9
#define ARR_MAX 5 //Maximum number of elem ents in
an arra y
ate <Cl ass T >
ternPl
T find -min (T ARR[) )
{
int i =0;
T MIN=ARR[O ) ;
for (i= l;i <ARR_MAX;i++)
if (ARR [i) <MIN )
MIN =AR R[i) ;
retu rn (MIN ) ;
)
int main ()
{
int I _MIN;
floa t F_MIN;
cha r C_MIN;
//D efin ing d i ffe ren t arra y type s
int 1(5] ={2 0 , 4,2 ,38 ,97 };
;
floa t F[S )={ -9 . 9, 12. 2, 3 . 1, 9 . 9, 8.9}
cha r C ( 5] = { ' a ' , ' A' ,
1 / , , , 4 , , ,_, } ;
y
//Fi ndi ng minimum val ue in each arra
I_M IN= find _mi n(I) ;
F_M IN= find _mi n(F) ;
C_MIN=find_mi n(C );
//P rin ting the res ult s
y= "<<I _MIN;
cou t << "Minimum val ue in inte ger arra
y= "<<F_MIN;
cou t << "\nM inim um val ue in floa t arra
cha ract er arra y = " « C_MIN;
cou t« "\nMinimurn valu e (as per ASCII) in
retu rn ( O) ;
obfect-Orlented ProgrommlM with c++

The output of Program 12.7 would be:


Minimum value i n integer array" 2
Minimum value i n float array" .9.9
Minimum va1ue (as per ASCII ) in character array , /

12.5 FUNCTION TEMPLATES WITH MULTIPLE PARAMETERS


ement .
Like template classes, we can use more than one genenc data type m the template stat ornrna·st

~
list as shown below: 'using a c

template<cJass Tl , class T2, ...>


ret urn t ype tunc ti onname (arguments of types Tl, T2, .. . )

{
(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!_.~ ·

#~nclude <iost ream>


#incl ude <String> -
using namespace s t d·I
. ate <cl ass Tl , c 1ass T2>
templ
void
{ display(Tl x, T2 y)

cout << x << \\ II


<< y << "\n" . 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

cout << "Call ' '


t empl ate wi th f loat and int eger type
p~ramet ers . ~~~n:~nction
,
d1spl a y (12 . 34 , 1234) 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'

" << X< < " \ n ",

tem pla te <C las ::: T , cl


as s Tl >
vo id di sp la y (T x , Tl // ov er lo ad ~d te m pl at
y) e fu nc tio n di sp la y
{ co u t< < "O ve rlo a de d
Te m pl ate Di sp la y 2: 11 11 11
<<:.<.<<" , <<Y<<" \ n ;

vo id di sp la y ( in t //o ve rlo ad ed ge ne ric


x ) di sp la y fu nc tio n

co ut << "E xp lic it di 11 11


sp la y: << X< <" \ n ;

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!~

Templ a t e <c la s s T>


: : fun_c tio nn ame (ar gl i st)
re tur nty pe cla ss name <T>
{
II ... . .
I I Fu nc tio n bo dy
II ... ..

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

II Member f unct ion te mpla tes ... . . .


t emp la te <c las s T>
..
ve c t or <T> ..
{ ve ctor( in t m)

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

1ate~ class T>


cen1f' r<:T> . . operator* (vector & y)
1 vecto
{ T sum= O;
f or(int i = O; i < size; i++ )
sum+= this - > v [i] * Y-V[i];
return sum;

S NON-TYPE TEMPLATE ARGUMENTS


12· that a template can have multiple aroument .
. h3\·e seen o s. 1t is also possible t
11e the type argument T, we can also use other aroum o use non-type arguments. That is. in
i;rion 10 o ents such as strinos f .
;dUJ . • rypes. Consider the following example: 0
' unction names. constant expressions
dbllllt•IO
)11 m ' •
ate<:clas s 1, int size>
temp l
class array

T a [size] ;
II automatic array initialization
I I ... ..
II .....
};

Th1·s template supplies the size of the array as an argument. This im r th h . .


. . . P ies at t e size of the array 1s known to the
iler at the compile time itself. The arguments must be specified whenever a t .
comP emp1ate c1ass 1s created. Example:
array<int,1 0> al; II Arr ay of 10 integers
array<float,5> a2; II Array of s floats
array<char, 2 0> a3; I I String of s i ze 20
Thesize is given as an argument to the template class.

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

Remembering f Understanding Q,_

V r: r)r . C I <.~
DEBUGGING E1,r_ ,\..,IJ ___)

l!.I Identify the error in the following program.

l:incl ud . n:·t , C', 111


<1

uni11g 11c1rn( ·,..,p 1<, : , cJ;


cl ass TP ::.:r

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;

12.2 Identify the error in the following program.


#include <iostream>
using namespace std;
template <class Tl, class T2>
class Person
{
Tl m_tl;
T2 m_t2;
public:
Person (Tl tl, T2 t2)
{
m tl = tl;
m t2 t2;
cout << m tl << \I II << m_t2 ·< < endl;

{erson (T2 t2, Tl t l)

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

cout << ++MinMax(2, 3);


return o,·

Find errors, if any, in the following code segment.


12.4
ternplate<class T>
T max(T, T)
{ ..... } ;
unsigned int m;
int main ()

max (m, 1 OO) ;

• Identify the error in the following program.


12•J
#include <iostream>
using namespace std;
template<class Tl=int, class T2>
class Test

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 >

usi ng namespace std ;

templa te<cla ss T>


vo i d fun{T arg l, int arg 2)
{
end l;
cou t << "Fun 1: " << arg l << " " << arg 2 <<
}

tem pla t e<c las s Tl, cla ss T2>


voi d fun{ Tl arg l, T2 arg 2)
{
cou t << "Fun 2: " << arg l << " " << arg 2 << end l;
}

voi d fun {in t arg l, int arg 2)

"Fun 3 .· arg l << " " << arg 2 << en dl;


11
cou t << <<

int main {)
371

I .
Whal will happen when the following pro ra
,~) g rn is executed?.
ude - ')' r ~ r:.cn, •
~i n<: l

]at~ c~la ss T int~


ternP
voJ.d fun( T -3.-ry l, int. ar92 )

cout ,,.,,. "Fun 1: " <,,, arg1 <, ,. ,,


<-: a ra2 <.-: er.al :
-

temp latec clas s TJ , clas s T 2 >


void fun (Tl a.r-g .l, T2 arg2 )

cout << "~ur i 2 : II


<< argJ . << " ti
<< arg 2 ""< endl · I

void fun( i nt arg l = 30 , in t arg 2 = 35 )


{
cou t << ''Fun 3: 11 << arg l << 11 "<< arg2 << en::H ;
}

int main ()
I
\
fun (25 , 281
fun ( 2 5 / 2 8 • (j I I

fun f25. 0 , 28)


fun ( J ;
fun< 4 5 J ;
r::=turn O ;

J2J What will happen when the following program is execu


ted?

11 1 ric 1 ud<"= .-- 1 or_; c .cc,., 111;,

t:c.rr ,pLH c ---clu.~ .... T = rloa t:.>


~1.,c;:; 1-.

_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

You might also like