You are on page 1of 23

78 Object Oriented Programming Concept Using C++

Unit 4: Functions
Notes
Structure
4.1 Introduction
4.2 The Main Function
4.3 General Form of a Function
4.4 Scope Rule of Functions
4.5 Simple Function
4.5.1 The Function Declaration
4.5.2 Calling the Function
4.5.3 The Function Definition
4.5.4 Eliminating the Declaration
4.6 Passing Arguments to Function
4.6.1 Passing Constants
4.6.2 Passing Variables
4.6.3 Passing by Value
4.6.4 Returning Values from Functions
4.6.5 Eliminating Unnecessary Variables
4.7 Reference Arguments
4.7.1 Passing Simple Data Types by Reference
4.8 Overload Functions
4.8.1 Different Number of Arguments
4.9 Inline Functions
4.9.1 Default Arguments
4.10 Return by Reference
4.11 Programming style
4.11.1Values vs. Identities
4.12 Access specifiers
4.13 Summary
4.14 Check Your Progress
4.15 Questions and Exercises
4.16 Key Terms
4.17 Further Readings

Objectives
After studying this unit, you should be able to:
• Understand the Simple function.
• Learn about arguments.

Amity Directorate of Distance & Online Education


Functions 79
• Understand about reference variable and arguments.
• Learn about function overloading. Notes

4.1 Introduction
A function groups a number of program statements into a unit and gives it a name. This
unit can then be invoked from other parts of the program.
Functions play an important role in program development. Dividing a program into
functions is one of the major principles of structured programming. Another use of
functions is that they reduce the size of a program by calling and using them at different
places in the program. Any sequence of instructions that appears in a program more
than once is a candidate for being made into a function. The function's code is stored
once in the memory, even though it is executed many times in the course of the
program.
Functions continue to be the building blocks of C++ programs. They serve the
same purpose as subprograms and procedures in BASIC. Infact, C++ has added many
new features to functions to make them more reliable and flexible.

4.2 The Main Function


The main () function is the starting point for the execution of a program. The definition
of main() would look like this in ANSI C as it does not return any value.
main()
{
// main program statements.
}
In C++, the main() returns a value of type int to the operating system. The
functions that have a return value should use the return statement for termination. The
main() function in C++ is, therefore, defined as follows:
int main()
{
----------
----------
return (o);
}
Since the return type of function is int by default, the keybord int in the main()
header is optional. But it is good programming practice to actually return a value from
main().
An exit value of zero mean that the program run successfully, while a non zero
value means there was a problem. The explicit use of a return(o) statement will
indicate that the program was successfully executed.

4.3 General Form of a Function


The general form of a function is return-type function-name (parameter list)
{
// Body of the function
}

Amity Directorate of Distance & Online Education


80 Object Oriented Programming Concept Using C++

The return-type specifies the type of data that the function returns. A function
may return any type of data except an array. The Parameter-list is a comma-separated
Notes list of variables names and their associated types that receive the values of the
arguments when the function is called. A function may be without parameter in which
case the parameter list is empty. However, even if there are no parameters, the
parentheses are still required. All function parameters must be declared individually,
each including both the type and name. The general form of a parameter declaration list
is:
f (type Var 1, type 2, ----------- type var n)
for example
f (int i, j, float k) [* incorrect*]
f (int i, int j, float k) [* correct*]

4.4 Scope Rule of Functions


Each function is a discrete block of code. A function's code is private to that function
and cannot be accessed by any statement in any other function except through a call to
that function. The code that constitutes the body of a function is hidden from the rest of
the program and, unless it uses global variables or data, it can neither affect nor be
affected by the other parts of the program.
Variables that are defined with in a function are called local variables. A local
variable comes into existence when the function is entered and is destroyed upon exit.
The only exception to this rule is when the variable is declared with the static storage
class specifier. This causes the compiler to treat the variable as if it were a global
variable for storage purposes, but limits its scope to with in the function.
In C++ you cannot define a function with in a function. This is why C++ is
technically not a block structured language.

4.5 Simple Function


Let us demonstrate a simple function whose purpose is to print a line with 40 asterisks.
The example program generates a table and lines of asterisks are used to make the
table more readable.
// simple function demonstration
# include <iostream h>
void asterisk ();
void main ()
{
asterisk (); // call to function.
cout <<" Name class " <<endl;
asterisk (); // call to function.
cout <<" Pooja 1X"<<endl;
cout <<" Neha X" << endl;
cout <<" Radha 1X" <<endl;
asterisk (); // call to function
}
void asterisk ()
{
for (int i = 0; i<40; i++)
{
Amity Directorate of Distance & Online Education
Functions 81
cout <<'*'
}
Notes
cout <<endl;
}
The output of the above program is:
****************************************************************************
Name Class
****************************************************************************
Pooja IX
Neha X
Radha IX
*****************************************************************************
The program consist of two functions; main () and asterisk (). You have already
seen many programs that use main() alone. The other components necessary to add a
function to the program are:
1. The function declaration.
2. The calls to the function.
3. The function definition.

4.5.1 The Function Declaration


Just as you cannot use a variable without first telling the compiler what it is, you also
cannot use a function without telling the compiler about it. The most common approach
is to declare the function at the beginning of the program. In the example program the
function asterisk() is declared in the line,
void asterisk();
The declaration tells the compiler that at some later point we plan to present a function
called asterisk. The keyword void specifies that the function has no return value, and
the empty parentheses indicate that it takes no arguments.
Notice that the function declaration is terminated with a semicolon. It is a complete
statement in itself. Function declarations are also called prototypes, since they provide
a model or blueprint for the function.

4.5.2 Calling the Function


The function is called (or invoked, or executed) three times from main(). Each of the
three calls looks like this:
asterisk();
This is all we need to call the function: the function name, followed by
parantheses. The syntax of the call is very similar to that of the declaration, except that
the returntype is not used. The call is terminated by a semicolon. Executing the call
statement causes the function to execute; that is, control is transferred to the function,
the statements in the function definition are executed, and then control returns to the
statement following the function call.

4.5.3 The Function Definition


The definition contains the actual code for the function. The definition for asterisk() is:

Amity Directorate of Distance & Online Education


82 Object Oriented Programming Concept Using C++

void asterisk() // declarator


{
Notes
for (int i=o; i < 40; i++)
{
cout <<'*' ;
}
cout<<endl;
}
The definition consists of a line called the declarator, followed by the function
body. The function body is composed of the statements that make up the function,
delimited by braces. The declarator must agree with the declaration i.e. it must use the
same function name, the same argument types in the same order and the same return
type.
Notice that the declarator is not terminated by a semicolon.
When the function is called, control is transferred to the first statement in the function
body. The other statements in the function body are then executed, and when the
closing brace is encountered, control returns to the calling program.

4.5.4 Eliminating the Declaration


You can eliminate the function declaration if the function definition appears in the listing
before the first call to the function. For example, we could rewrite our first example
program as follows:
// eliminating function declaration
# include <iostream.h>
void asterisk() // function
definition
{
for (int i = 0; i < 40; i++)
{
cout <<'*';
}
cout <<endl:
}
void main () //main follows
function
{
asterisk(); // call to function
cout <<"Name Class"<<endl;
Cout<<" Pooja 1x"<<endl;
Cout<<" Neha x"<<endl;
Cout <<" Radha 1x"<<endl;
asterik(); // call to
function.
}

Amity Directorate of Distance & Online Education


Functions 83
This approach is simpler for short programs as it removes the declaration, but it is
less flexible. In general we will stick with the first approach using declarations and
starting the listing with main(). Notes
Fast review:
Function Prototype:
type function_name(type_1 v1, type_2 *v2, type_3 &v3, const
type_4 v4);
// e.g. char * strcpy(char * s1, const
char * s2);
// *v2 says pass a pointer to v2
// &v3 says pass by reference
// const type_4 v4 says v4 is an 'in'
parameter a prefix of static makes the
function visible only in this file
Function Definition:
type function_name(int a, float b, const char * ch,...){
function_body }
// only parameters passed by pointer or
// reference can
// be modified in the calling function,
// a local copy will be made and can be
//modified,
// unsafely, unless const is used
char * strcpy( char * s1, const char * s2 ) { statements }
Obsolete example of a function and call passing the address of
a scalar
void func(int *num)
{
*num *= *num; // square num back in its place
} ...
func(&i); // call, passing address of i, the lvalue of i (
yuk!)
C++ example of a function and call passing a reference of a
scalar
void func(int &num) // says do type checking and pass by
//reference
{
num = num*num; // square num back in its place
}
func(i); // just a normal call, the compiler knows
to pass a reference

Amity Directorate of Distance & Online Education


84 Object Oriented Programming Concept Using C++

4.6 Passing Arguments to Function


Notes An argument is piece of data (for example an int value) passed from a program to the
function. Arguments allow a function to operate with different values, or even to do
different things, depending on the requirements of the program calling it.

4.6.1 Passing Constants


Let us modify our previous asterisk function, which is too rigid. Instead of a function that
always prints 40 asterisks we want a function that will print any character, any number
of times. We use arguments to pass the character to be printed and the number of
times to print it.
//demonstrates function arguments.
# include <iostream.h>
void repeat (char, int); // function declaration
void main()
{
repeat ('-', 45 ); //call to function
cout <<"Name class"<<endl;
repeat ('=', 20); // call to function.
cout<<"Pooja 1x"<<endl;
cout<<"Neha x"<<endl;
cout<<"Radha 1x"<<endl;
repeat ('$', 30); // call to function
// function definition
void repeat (char ch, int n) //function declarator
{
for (int i = 0; i<n; i++)
{
cout<<ch;
}
cout <<endl;
}
The new function is call, specific values (constants in this case) are inserted in the
appropriate place in the parentheses:

repeat (',', 45);


This statement instructs repeat() to print a line of 45 dots. The types in the declaration
and the definition must also agree.
The next call to repeat(),
repeat ('=', 20);
tells it to print 20 equal signs. The third call again prints 30 dollar signs. The output of
above program is:

Amity Directorate of Distance & Online Education


Functions 85
.....................................................................................................................................
Name Class Notes
=============================================
Pooja IX
Neha X
Radha IX
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
The variable used with in the function to hold the argument values are called
parameters; in repeat() they are ch and n. The parameter names, ch and n are used in
the function as if they were normal variables. Placing them in declarator is equipment to
defining them with statements like:
char ch;
int n;
When the function is called, its parameters are automatically initialized to the
values passed by the calling program.

4.6.2 Passing Variables


In the above example the arguments were constants: '.', '45', '=' and so on.
Let us look at an example where variable, instead of constants are passed as
arguments. Let the user specify the character and the number of times it should be
repeated.
// demonstrates variable arguments.
# include <iostream.h>
void repeater (char, int); // function declaratlion void
main()
{
char chn;
int nn;
cout<<"Enter a character:";
cin >>chn;
cout<<" Enter number of times to repeat it:";
cin>>nn;
repeater (chn, nn); // function call
}
// function definition
void repeater (char ch, int n)
{
for (int i = 0; i<n; i++)
{
cout<<ch;

Amity Directorate of Distance & Online Education


86 Object Oriented Programming Concept Using C++
}

Notes cout <<endl;


}
The output of the above program is:
Enter a character:–
Enter number of times to repeat it:10
-----------------
Here chn and nn in main() are used as arguments to repeater():
repeater (chn, nn);
The data types of variables used as arguments must match those specified in the
function declaration and definition, i.e., chn must be a char and nn must be an int.

4.6.3 Passing by Value


In the above exmaple the particular values possessed by chn and nn when the function
calls is executed will be passed to the function. The function creates new variables ch
and n to hold the values of these variable arguments. It initializes these parameters to
the values passed. They are then accessed like other variables by statements in a
function body. Passing arguments in this way where the function creates copies of the
arguments passed to it is called passing by value.

4.6.4 Returning Values from Functions


When a function completes its execution it can return a single value to the calling
program. This return value consists of an answer to the problem the function has
solved. Our next example demonstrates a function that returns a weight in kilograms,
after being given a weight in pounds.
// demonstrates return values
#include<iostream.h>
float pdtokg (float);
void main()
{
float pds, kgs;
cout<<"\n Enter weight in pounds";
cin >> pds;
kgs = pdtokg (pds);
cout <<"weight in kilograms is" <<kgs;
}
// function definition
float pdtokg (float pounds)
{
float kilograms - 0.453592* pounds;
return kilograms;
}
Amity Directorate of Distance & Online Education
Functions 87
The output of above program is:
Enter weight in pounds. : 182 Notes
Weight in kilograms is________________
When a function returns a value, the data type of this value must be specified. The
function declaration does this by placing the data type float in this case, before the
function name the declaration and the definition. In the declaration of the function float
pdtokg (float);
The first float specifies the return type. The float in parentheses specifies the argument
type.
While many arguments may be sent to a function. Only one argument many be returned
from it. This is a limitation when you need to return more values. The pdtokg() function
return kilograms which is of type int.
You should always include a function's return type in the function declaration. If the
function doesn't return anything, use the keyword void to indicate the same. The default
return type is int in C++. If you don't use a return type in the declaration, the compiler
will assume that the function returns an int value.

4.6.5 Eliminating Unnecessary Variables


The above conversion program contains several variables that were used for clarity but
are not really necessary. A variation of this program is given below.
// elimination of unnecessary variables
# include <iostream.h>
float pdtokg (float);
void main()
{
float pds;
cout <<"\n Enter weight in pounds:";
cin >> pds;
cout <<" weight in kilograms in" <<pdtokg (pds;)
}
// function definition
float pdtokg (float pounds)
{
return 0.453592 * pounds;
}
In main() the variable kgs from the previous program has been eliminated. Also in the
pdtokg() function the variable kilograms is no longer used. The expression
pdtokg(pds) is inserted directly into the cout statement. The expression
0.453592*pounds is inserted directly into the return statement:
return 0.453592 * pounds;
The calculation is carried out, and the resulting value is returned to the calling program,
just as the value of a variable would be.

Amity Directorate of Distance & Online Education


88 Object Oriented Programming Concept Using C++

4.7 Reference Arguments


Notes A reference provides an alias – a different name- for a variable. The most important use
for references is in passing arguments to functions.
Passing arguments by reference uses a different mechanism from that of passing
argument by values. Instead of a value being passed to the function, a reference to the
original variables, in the calling program is passed.
The primary advantage of passing by reference is that the function can access the
actual variables in the calling program. It also provides a mechanism for returning more
than one value from the function back to the calling program.

4.7.1 Passing Simple Data Types by Reference


Consider the example given below which shows a simple variable passed by
references:
// demonstrates passing by references.
# include <iostream.h>
void main()
{
void fracint (float, floats, floats);
// prototype.
float numb, intpart, fracpart;
do
{
cout <<"\n Enter a real number:";
cin >>numb;
fracint (numb, intpart, fracpart);
cout <<" fraction part is" << fracpart
<<"Integer part is" << int part;
} while (numb 1=0);
}
// fracint ()
void fracint (flaot n, float & intp, float & fracp)
{
intp=float (long (n));
fracp = n-intp;
}
The main() part of this program asks the user to enter a number of type float. The
program will separate this number into an integer and fractional part. To find these
values, main() calls the function fracint(). The output of the above program is:
Enter a real number: 78.43
Fractional part is 0.43 Integer part is 78.

Amity Directorate of Distance & Online Education


Functions 89
The fracint() function can find the integer and fractional parts. It could use a return
statement to return one value but not both. But how can it return two values? The
problem is sloved using reference arguments. The declarator for the function is: Notes
void fracint (float n, float & intp, float & fracp)
Reference arguments are indicated by the ampersand (&) following the data type of the
argument:
float & intp
The & indicates that intp is an alias for whatever variables is passed as an argument. It
means that intp is a reference to the float variable passed to it. The function declaration
shows the use of the ampersand in the definition:
void fracint (float, float &, float &):
As in the definition, the ampersand follows those arguments that are passed by
reference.
The ampersand is not used in the function call:
fracint (numb, intpart, fracpart):
From the function call alone there is no way to tell whether an argument will be passed
by reference or by value.
Intp and intpart are different names for the same place in the memory, as are fracp
and fracpart. The parameter n in fracint() is a separate variable into which the value of
numb is capital. It can be passed by value because the fracint() function doesn't need
to modify numb.

4.8 Overload Functions


An overload function appears to perform different activities depending on the kind of
data sent to it.
It may seem mysterious how an overloaded function knows what to do. It performs
one operation on one kind of data but another operation on a different kind.

4.8.1 Different Number of Arguments


Recall the asterisk() function and the repeater() function both shown earlier in this
chapter. The asterisk() function printed a line using 40 asterisks, while repeater() used
a character and a line length that were both specified when the function was called.
Imagine a third function charline(), that always print 40 characters but allows the calling
program to specify the character to be printed. These three functions – asterisk(),
repeater() and charline() perform similar activity but have different names. It would be
far more convenient to use the same name for all three functions, even though they
each have different arguments. Here's a program that makes it possible:
// demonstrates function overloading
# include <iostream.h>
voidrepchar();
voidrepchar (char);
voidrepchar (char, int);
voidmain()
{
repchar ();

Amity Directorate of Distance & Online Education


90 Object Oriented Programming Concept Using C++
repchar ('+');

Notes repchar ('=', 25);


}
// repchar () - displays 40 asterisks
void repchar()
{
for (int i=0, i<40; i++)
cout <<'*';
cout <<endl;
}
// repchar() - displays 40 copies of specified
// character.
void repchar (char ch)
{
for (int i = o; i<40; i++)
cout <<ch;
cout <<endl;
}
// repchar () - displays specified number of copies of
specified
// character.
void repchar (char ch, int n)
{
for (int i = o; i<n; i++)
cout <<ch;
cout << endl;
}
The output of this program is:
*****************************************************************************
++++++++++++++++++++++++++++++++++++++++++++++++
================================================
The first two line are 40 characters long and the third is 25.
The program contains three functions with the same name. It uses the number of
arguments, and their data types, to distinguish one function from another. The
declaration,
void repchar();
which takes no arguments, describe an entirely different function then the declaration ,
void repchar (char, int);

Amity Directorate of Distance & Online Education


Functions 91
which takes one argument of type char and another of type int.
The compiler sets up a seprate function for every function with the same name but Notes
different number of arguments. This process is called function overloading.
The compiler can also distinguish between overloaded functions with the same
number of arguments, provided their type is different. Different functions are used
depending upon the type of argument.
Overloaded functions can simplify the programmer's life by reducing the number of
function names to be remembered.

4.9 Inline Functions


One of the objectives of using functions in a program is to save memory space, which
becomes appreciable when a function is likely to be called many times. However,
everytime a function is called, it takes a lot of extra time in executing a series of
instructions for tasks such as jumping to the functions, saving registers, pushing
arguments into the stack and returning to the calling function. All these instructions slow
down the program.
C++ has a solution to solve this problem. To eliminate the costs of calls to small
functions, C++ proposes a new feature called inline functions. As inline function is a
function that is expanded in line when it is invoked. That is, the compiler replaces the
function call with the corresponding function code. Functions that are very short, say
one or two statements, are candidates to be inlined. The inline functions are defined as
follows:
inline function – header
{
----------------
// function body
----------------
}
Here's a variation of conversion program that converts weight in pounds to
kilograms:
// demonstrates inline functions
# include <iostream.h>
// pdtokg() - definition of function.
inline float pdtokg (float pounds)
{
return 0.453592 * pounds;
}
void main ()
{
float pds;
cout <<"\n Enter weight in pounds:';
cin >> pds;
cout <<"weight in kilograms is"<<pdtokg
(pds);
}

Amity Directorate of Distance & Online Education


92 Object Oriented Programming Concept Using C++

To make a function inline, the keyword inline is needed in the function definition:
inline float pdtokg (float pounds)
Notes
In INLINE, we must place the definition of function before main(). This is because
the compiler must insert the actual code into the program, not just instructions to call the
function.
Be aware that the inline keyword is actually just a request to the compiler.
Sometimes the compiler will ignore the request and compile the function as a normal
function.

4.9.1 Default Arguments


C++ also allows us to call a function without specifying all its arguments. In such cases,
the function assigns a default value to the parameter which does not have a matching
argument in the function call. Default values are specified when the function is declared.
The compiler looks at the prototype to see how many arguments a function uses and
alerts the program for possible default values. Here's an example:
// demonstrates missing and default arguments
# include <iostream.h>
// prototype with default arguments.
void repchar (char - ' * ', int = 40); void main()
{
repchar (); // prints 40 asterisks.
repchar ('+'); // prints 40 plus signs.
repchar (' = ', 20); // prints 20 equal
signs.
}
// repchar()
void repchar (char ch, int n)
{
for (int i=o; i<n; i++)
cout <<ch;
cout << endl;
}
The default value is specified in a manner syntactically similar to a variable
initialization. The above example declares defasult values in function declaratin:
void rep char (char = '*', int = 40);
The above prototype declares a default value of '*' to argument char and value 40 to
argument int. The default argument follows an equals sign, which is placed directly after
the type name.
If one argument is missing when the function is called, it is assumed to be the last
argument. If both arguments are missing, the function assigns the default value '*' to ch
and '40' to n. Thus all the three calls to the function work, even though each has a
different number of arguments.
Remember that missing arguments must be those at the end of the arguments list. You
can not leave out any middle argument. If you left out some in the middle, the compiler
will flag an error.

Amity Directorate of Distance & Online Education


Functions 93
Default arguments are useful if you just don't want to go to the trouble of writing
arguments that almost have the same value. Advantages of providing the default
arguments are: Notes
1. We can use default arguments to add new parameters to the existing functions.
2. Default arguments can be used to combine similar functions into one.

4.10 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 y;
}
Since the return type of max () is int &, the function returns reference to x or y (not
the values). Then a function call such as max (a, b) will yield a reference to either a or b
depending on their values. This means that this function call can appear on the left-
hand side of an assignment statement. That is the statement;
max (a, b) = 1;
is legal and assign 1 to a if it is larger, otherwise 1 to b.

4.11 Programming style


C++ is a systems-level language which provides the high-level abstractions with very
low (often zero) runtime cost. The paradigms which commonly associated with C++
include procedural, object-oriented and generic programming.

4.11.1 Values vs. Identities


Simple values such as 1, 2 and 3 are easy to identify, as these are constant integer
values. This would be redundant; however, because all values are actually constants
and the values never change, but the value associated with an identity may change.
The code shown below demonstrates a simple use of a value type.
void Foo()
{
for (int x = 0; x < 10; ++x)
{
// Call Bar, passing the value of x and not the
identity
Bar(x);
}
}
void Bar(int y)
{

Amity Directorate of Distance & Online Education


94 Object Oriented Programming Concept Using C++
// Display the value of y

Notes cout << y << " ";


// Change the value that the identity y refers to
// Note: This will not affect the value that the
variable x refers to
y = y + 1;
}
// Outputs:
// 0 1 2 3 4 5 6 7 8 9
With only a small change, the variable y can become a reference type which drastically
changes the relationship between x and y, as shown in code below
void Foo()
{
for (int x = 0; x < 10; ++x)
{
// Call Bar, passing the identity of x
Bar(x);
}
}
void Bar(int& y)
{
// Display the value of y
cout << y << " ";
// Change the value that the identity y refers to
// Note: This will affect the variable x
y = y + 1;
}
// Outputs:
// 0 2 4 6 8
C++ also provides the const modifier, which prevents the programmer from making
changes to a variable and thus further preserves the concept of a value, this is shown
on program explained below:
void Foo()
{
for (int x = 0; x < 10; ++x)
{
// Call Bar, passing the identity of x,
// yet the value of x will be protected by the const

Amity Directorate of Distance & Online Education


Functions 95
Bar(x);
} Notes
}
void Bar(const int& y)
{
// Use the value of y
cout << y << " ";
// Attempt to change the value of what the identity y
refers to
y = y + 1; // This line will not compile because y is
const!
}
Note in program above y is passed by reference, the value of y is protected at compile
time by a const modifier. This gives C++ programmers an efficient method of passing
large objects while working with their values as opposed to their identities.
With the const modifier, C++ has immutable data types that resemble those found in
most functional programming languages.

4.12 Access specifiers


Access specifiers define the access rights for the statements or functions that follows
it until another access specifier or till the end of a class. The three types of access
specifiers are "private", "public", "and protected".

Private:

The members declared as "private" can be accessed only within the same class and not
from outside the class.

Public:

The members declared as "public" are accessible within the class as well as from
outside the class.

Amity Directorate of Distance & Online Education


96 Object Oriented Programming Concept Using C++

Notes

Protected:

The members declared as "protected" cannot be accessed from outside the class, but
can be accessed from a derived class. This is used when inheritaance is applied to the
members of a class.

The members declared as "public" are accessible within the class as well as from
outside the class.

4.13 Summary
A function is a group of statements that together perform a task. Every C++ program
has at least one function, which is main(), and all the most trivial programs can define
additional functions. You can divide up your code into separate functions. How you
divide up your code among different functions is up to you, but logically the division
usually is so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters. A function definition provides the actual body of the function. The C++
standard library provides numerous built-in functions that your program can call. For
example, function strcat() to concatenate two strings, function memcpy() to copy one
memory location to another location and many more functions. A function is knows as
with various names like a method or a sub-routine or a procedure etc

4.14 Check Your Progress


Multiple Choice Questions
1. Where does the execution of the program starts?
a) user-defined function
b) main function
c) void function
d) none of the mentioned

2. What are mandatory parts in function declaration?


a) return type,function name
b) return type,function name,parameters

Amity Directorate of Distance & Online Education


Functions 97
c) both a and b
d) none of the mentioned
Notes
3. which of the following is used to terminate the function declaration?
a) :
b) )
c) ;
d) none of the mentioned

4. How many max number of arguments can present in function in c99 compiler?
a) 99
b) 90
c) 102
d) 127

5. Which is more effective while calling the functions?


a) call by value
b) call by reference
c) call by pointer
d) none of the mentioned

6. What is the output of this program?

#include <iostream>

using namespace std;

void main()

void main()

cout<<"hai";

int main()

mani();

return 0;

}
a) Hai
b) haihai
c) compile time error
d) none of the mentioned

Amity Directorate of Distance & Online Education


98 Object Oriented Programming Concept Using C++

7. What is the output of this program?


Notes
#include <iostream>

using namespace std;

void fun(int x, int y)

x = 20;

y = 10;

int main()

int x = 10;

fun(x, x);

cout << x;

return 0;

}
a). 10
b). 20
c). compile time error
d). none of the mentioned

8. What is the scope of the variable declared in the user definied function?
a) whole program
b) only inside the {} block
c) both a and b
d) none of the mentioned

9. How many minimum number of functions are need to be presented in c++?


a) 0
b) 1
c) 2
d) 3

10. What is this operator called?:?


a) Conditional
b) relational

Amity Directorate of Distance & Online Education


Functions 99
c) casting operator
d) none of the mentioned
Notes
4.15 Questions and Exercises
1. Write a function called bloom() that displays the word bloom.
2. What is the purpose of using argument names in a function declaration?
3. What is the significance of empty parentheses in a function declaration?
4. How many values can be returned from a function?
5. Where is a function's return type specified?
6. What is the reason for passing arguments by reference?
7. What do you understand by function overloading? Write declarations for two
overload functions named par (). Both have return type int. The first takes one
argument of type float, and the second takes two arguments, one of type float
and other of type char. If this is not possible, say why?
8. When will you make a function inline? Why?

4.16 Key Terms

• Function: A function groups a number of program statements into a unit


and gives it a name.

• Main(): The main () function is the starting point for the execution of a
program

• Return type: The return-type specifies the type of data that the function
returns

• Parameter list: The Parameter-list is a comma-separated list of variables


names and their associated types that receive the values of the arguments
when the function is called.

• Local variable: Variables that are defined with in a function are called local
variables.

Check Your Progress: Answers


1. b) main function
2. a) return type, function name
3. c) ;
4. d) 127
5. b) call by reference
6. c) compile time error
7. a). 10
8. b) only inside the {} block
9. b) 1
10. a) Conditional

Amity Directorate of Distance & Online Education


100 Object Oriented Programming Concept Using C++

4.17 Further Readings


Notes z Let Us C++ by yashwant karnetkar.
z Balagurusamy (2008) Object Oriented Programming With C++ Tata McGraw-Hill
Education.
z Subhash, K. U. (2010) Object Oriented Programming With C++ Pearson Education
India.

Amity Directorate of Distance & Online Education

You might also like