You are on page 1of 31

1

OBJECT-ORIENTED PROGRAMMING
(OOP) WITH C++

Lecture-4
Chapter -5
Bilal Munir Mughal
FUNCTIONS
2

1. Simple Functions
2. Passing Arguments to Functions
3. Returning Values from Functions
4. Reference Arguments
5. Overloaded Functions
6. Recursion
7. Inline Functions
8. Default Arguments
9. Scope and Storage Class
10. Returning by Reference
11. const Function Arguments
FUNCTION?
3

 A function groups a number of program statements into a unit


and gives it a name
 The function can be invoked from other parts of the program
 dividing a program into functions is one way to structure your
program (structured programming)
 The function’s code is stored in only one place in memory,
even though the function is executed many times in the course
of the program.
FUNCTION?
4

 A function definition contains the body of the function


 A function declaration (also called prototypes) specifies the
name of the function the type of the value returned and the
number and type of arguments (also referred as function
signature) that must be supplied in a call of the function
 to call the function all we need is the function name,
followed by parentheses
 must declare or define the function before it is called
SIMPLE FUNCTIONS
#include <iostream>
using namespace std;
void starline(); //function declaration(prototype)
int main()
{
starline(); //call to function
cout << "Data type Range" << endl;
starline(); //call to function
cout << "char -128 to 127" << endl
<< "short -32,768 to 32,767" << endl
<< "int System dependent" << endl
<< "long -2,147,483,648 to 2,147,483,647" << endl;
starline(); //call to function
return 0;
}
//--------------------------------------------------------------
// starline()function definition
void starline() //function declarator
{
for(int j=0; j<45; j++) //function body
cout << '*';
cout << endl; }
SIMPLE FUNCTIONS
#include <iostream>
using namespace std;
// starline() function definition
void starline() //function declarator
{
for(int j=0; j<45; j++) //function body
cout << '*';
cout << endl;
}
int main()
{
starline(); //call to function
cout << "Data type Range" << endl;
starline(); //call to function
cout << "char -128 to 127" << endl
<< "short -32,768 to 32,767" << endl
<< "int System dependent" << endl
<< "long -2,147,483,648 to 2,147,483,647" << endl;
starline(); //call to function
return 0;
}
PASSING ARGUMENTS TO
FUNCTIONS
 An argument is a piece of data(an int value, for example)
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.

 As an example, let’s suppose we decide that the


starline() function in the last example is too rigid. Instead
of a function that always prints 45 asterisks, we want a
function that will print any character any number of
times.
PASSING ARGUMENTS TO
FUNCTIONS(Passing Constants)
#include <iostream>
using namespace std;
void repchar(char, int); //function declaration
int main()
{
repchar('-', 43); //call to function
cout << "Data type Range" << endl;
repchar('=', 23); //call to function
cout << "char -128 to 127" << endl
<< "short -32,768 to 32,767" << endl
<< "int System dependent" << endl
<< "double -2,147,483,648 to 2,147,483,647" << endl;
repchar('#', 43); //call to function
return 0;
}
//--------------------------------------------------------------
// repchar() function definition
void repchar(char ch, int n) //function declarator
{
for(int j=0; j<n; j++) //function body
cout << ch;
cout << endl; }
PASSING ARGUMENTS TO
FUNCTIONS (Passing Variables)
#include <iostream>
using namespace std;
void repchar(char, int); //function declaration
int main()
{
char chin;
int nin;
cout << "Enter a character: ";
cin >> chin;
cout << "Enter number of times to repeat it: ";
cin >> nin;
repchar(chin, nin);
return 0;
}
//--------------------------------------------------------------
// repchar() function definition
void repchar(char ch, int n) //function declarator
{
for(int j=0; j<n; j++) //function body
cout << ch;
cout << endl;
}
PASSING ARGUMENTS TO
FUNCTIONS (Passing by Value)
 when constants are passed to the function:
 The function creates new variables to hold the values of these
variable arguments.
 The function gives these new variables the names and data types
of the parameters specified in the declarator: ch of type char and
n of type int.
 It initializes these parameters to the values passed. They are
then accessed like other variables by statements in the function
body.

 Passing arguments in this way, where the function creates copies of


the arguments passed to it, is called passing by value
PASSING ARGUMENTS TO
FUNCTIONS (Passing by Value)
RETURNING VALUES FROM
FUNCTIONS
 When a function completes its execution, it can return a single value
to the calling program.

 Usually this return value consists of an answer to the problem the


function has solved e.g. a function that returns a weight in kilograms
after being given a weight in pounds.

 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
before the function name in the declaration and the definition.
RETURNING VALUES FROM
FUNCTIONS
#include <iostream>
using namespace std;
float lbstokg(float); // data/return type float
int main()
{
float lbs, kgs;
cout << "\nEnter your weight in pounds: ";
cin >> lbs;
kgs = lbstokg(lbs); //the value returned by the function assigned to variable
cout << "Your weight in kilograms is " << kgs << endl;
return 0;
}
//--------------------------------------------------------------
// lbstokg() converts pounds to kilograms
float lbstokg(float pounds) //data/return type float
{
float kilograms = 0.453592 * pounds;
return kilograms; }
RETURNING VALUES FROM
FUNCTIONS (The return Statement)
 A return statement causes execution to leave the current function and
resume at the point in the code immediately after where the function
was called

 Return statements allow a function to specify a return value to be


passed back to the code that called the function.

 While many arguments may be sent to a function, only one


argument may be returned from it. This is a limitation when you
need to return more information and other approaches required e.g.
pass arguments by reference (discussed later)

 If the function doesn’t return anything, use the keyword void to


indicate this fact. If you don’t use a return type in the declaration, the
compiler will assume that the function returns an int value.
RETURNING VALUES FROM
FUNCTIONS (The return Statement)
 In previous program the return statement tells the function to return execution
of the program to the calling function, and report the value of variable
kilograms.
REFERENCE ARGUMENTS
 A reference provides an alias—a different name—for a variable.
One of the most important uses for references is in passing
arguments to functions.

 Passing arguments by reference uses a different mechanism. Instead


of a value being passed to the function, a reference to the original
variable, in the calling program, is passed. (It’s actually the memory
address of the variable that is passed)

 Important advantages of passing by reference


 the function can access the actual variables in the calling
program.
 provides a mechanism for passing more than one value from the
function back to the calling program.
REFERENCE ARGUMENTS
#include <iostream>
using namespace std;
int main()
{
void intfrac(float, float&, float&); //declaration
float number, intpart, fracpart; //float variables
do {
cout << "\nEnter a real number: "; //number from user
cin >> number;
intfrac(number, intpart, fracpart); //find int and frac
cout << "Integer part is " << intpart //print them
<< ", fraction part is " << fracpart << endl;
} while( number != 0.0 ); //exit loop on 0.0
return 0;
}
//--------------------------------------------------------------
void intfrac(float n, float& intp, float& fracp)
{
long temp = static_cast<long>(n); //convert to long,
intp = static_cast<float>(temp); //back to float
fracp = n - temp; //subtract integer part
}
REFERENCE ARGUMENTS
18
OVERLOADED FUNCTIONS
 An overloaded function appears to perform different activities
depending on the kind of data sent to it.
 to distinguish one function from another, compiler uses function’s
signature i.e.
 the number of arguments,
 their data types
 and order of arguments

void print(int a) // prints an integer


{
cout << ”integer : ” << a;
}

void print(string s) // prints a string


{
cout << ”string : ” << s;
}
OVERLOADED FUNCTIONS
#include <iostream> //--------------------------------------------------------------
using namespace std; // repchar() displays 45 copies of specified
void repchar(); //declarations character
void repchar(char); void repchar(char ch)
void repchar(char, int); {
int main() for(int j=0; j<45; j++) // always loops 45 times
{ cout << ch; // prints specified character
repchar(); cout << endl;
repchar('='); }
repchar('+', 30); //--------------------------------------------------------------
return 0; // repchar() displays specified number of copies of
} specified character
//------------------------------------------ void repchar(char ch, int n)
// repchar() displays 45 asterisks {
void repchar() for(int j=0; j<n; j++) // loops n times
{ cout << ch; // prints specified character
for(int j=0; j<45; j++) // always loops 45 cout << endl;
times }
cout << '*'; // always prints asterisk
cout << endl;
}
RECURSION

 Recursion involves a function calling itself.


#include <iostream> //-------------------------------------------------------
using namespace std; // factfunc()
unsigned long factfunc(unsigned // calls itself to calculate factorials
long); //declaration unsigned long factfunc(unsigned long n)
int main() {
{ if(n > 1)
int n; //number entered by user return n * factfunc(n-1); //self call
unsigned long fact; //factorial else
cout << "Enter an integer: "; return 1;
cin >> n; }
fact = factfunc(n);
cout << "Factorial of " << n << " is " << fact
<< endl;
return 0; }
INLINE FUNCTIONS

 To save execution time in short functions, you may elect to put the
code in the function body directly inline with the code in the calling
program.
 That is, each time there’s a function call in the source file, the actual
code from the function is inserted, instead of a jump to the function.
INLINE FUNCTIONS
#include <iostream>
using namespace std;
// lbstokg() converts pounds to kilograms
inline float lbstokg(float pounds)
{
return 0.453592 * pounds;
}
//--------------------------------------------------------------
int main()
{
float lbs;
cout << "\nEnter your weight in pounds: ";
cin >> lbs;
cout << "Your weight in kilograms is " << lbstokg(lbs)
<< endl;
return 0; }
DEFAULT ARGUMENTS

 A function can be called without specifying all its arguments.


 This won’t work on just any function: The function declaration must
provide default values for those arguments that are not specified.

#include <iostream> //------------------------------------------------------


using namespace std; // repchar() displays line of characters
void repchar(char='*', int=45); void repchar(char ch, int n)
//declaration with default arguments // defaults supplied if necessary
int main() {
{ for(int j=0; j<n; j++) //loops n times
repchar(); //prints 45 asterisks cout << ch; //prints ch
repchar('='); //prints 45 equal signs cout << endl;
repchar('+', 30); //prints 30 plus signs }
return 0; }
SCOPE AND STORAGE CLASS

In C++ scope and storage class are features related to the interaction of
variables and functions
The scope (visibility) of a variable determines which parts of the
program can access it,
and its storage class determines how long it stays in existence.

Scope
Local Scope Variables
 Variables with local scope are visible only within a block.
are not created until that block is executed.

File Scope Variables (Global Variables)


 Variables with file scope are visible throughout a file.
 defined outside of any function, (can also be defined outside of any
class)

Class Scope, discussed later


SCOPE AND STORAGE CLASS

Storage Class
The time period between the creation and destruction of a variable is
called its lifetime (or sometimes its duration).

The lifetime of a local variable coincides with the time when the function in
which it is defined is executing.

There are two storage classes: automatic and static, that determine the
lifetime of a local variable

Variables with storage class automatic exist during the lifetime of the
function in which they’re defined. All variables declared within a block of
code are automatic by default, but this can be made explicit with the
auto keyword
Variables with storage class static exist for the lifetime of the
program.
SCOPE AND STORAGE CLASS
27

Storage Types Summary


RETURNING BY REFERENCE

 One reason is to avoid copying a large object,


 Another reason is to allow you to use a function call on the left side
of the equal sign.
 treated as if it were a variable
 can’t return a reference to a local variable

#include <iostream>
using namespace std;
int x; // global variable
int& setx(); // function declaration
int main()
{ // set x to a value, using
setx() = 92; // function call on left side
cout << "x=" << x << endl; // display new value in x
return 0;
}
//--------------------------------------------------------------
int& setx()
{
return x; // returns the value to be modified }
const FUNCTION ARGUMENTS

 If an argument is large, passing by reference is more efficient


because, behind the scenes, only an address is really passed, not the
entire variable.
 Suppose you want to pass an argument by reference for efficiency,
but not only do you want the function not to modify it, you want a
guarantee that the function cannot modify it.
 To obtain such a guarantee, you can apply the const modifier to the
variable in the function declaration.
const FUNCTION ARGUMENTS
void aFunc(int& a, const int& b); //declaration
int main()
{
int alpha = 7;
int beta = 11;
aFunc(alpha, beta);
return 0;
}
//--------------------------------------------------------------
void aFunc(int& a, const int& b) //definition
{
a = 107; //OK
b = 111; //error: can’t modify constant argument
}
31

Q&A
?

You might also like