You are on page 1of 39

Chapter-2: C++ Functions

Mekelle Institute of Technology


Department of Computer Science and Engineering
Kifle B.N
(kifle.berhane@mu.edu.et)
Room#-100
Contents

 Function parameters and arguments


 Pass by value and reference

 Return by value and reference

 Inline functions

 Friend functions

 Overloaded functions

1-1 1
Function Parameters and arguments

 A function parameter (formal parameter) is a variable


declared in the function declaration. It is a receiving variable.
 Argument (actual parameter) is a value that is passed to the

function by the caller.


 The arguments of a function calling can be passed either

passing by value or passing by reference


Passing by value:
 A function parameter receives a copy of only the value of the

argument.
 As a result, if the function makes any changes to the

parameters, this will not affect the argument.

1-2 2
Example:
// function example
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}

1-3 3
Passing by Reference
 A reference parameter receives the address of the
argument
 The variable itself is passed to the function

 Any change made to a reference parameter directly

affects argument.
 In passing by reference, in function declaration the type of

each parameter must be followed by an ampersand sign


(&).
 This ampersand specifies that corresponding arguments

are to be passed by reference

1-4 4
Example: pass by reference

 The above function modifies parameters a, b


and c, correspondingly, values of x, y and z is
also modified.
 Passing by reference is also an effective way to
allow a function to return more than one value
1-5 5
Return by Value and By Reference
Return by Value
 A copy of value is returned to the caller.

Example:
int doubleValue(int x)
{
int value = x * 2;
return value ; // A copy of value will be returned here
} // value goes out of scope here

1-6 6
Return by value…
 When to use return by value:
 To return variables declared inside the function
 To return arguments that were passed by value
 When not to use return by value:

 To return pointer (use return by address)


 To return a large struct or class (use return by
reference)

1-7 7
Return by Reference
include <iostream>
using namespace std;
• The return type of function test() is int& int n;
• The return statement is return n; it returns int& test();
variable n itself.
int main() {
• Then the variable n is assigned to the left
test() = 5;
side of code test() = 5; and value of n is
displayed cout<<n;
• Similar to pass by reference, values return 0; }
returned by reference must be variables
int& test() {
• Return by reference is also fast, which can
return n;
be useful when returning structs and
classes. }
1-8 8
Consider the following example:

 Don’t return local variables to the function by


reference. int& doubleValue(int x)
{
int value = x * 2;
return value; // return a ref
erence to value here
} // value is destroyed here

 value should be a global variable


 Return by reference is used to return arguments

passed by reference
1-9 9
Global vs local variables
 The scope of variables declared within a function or any
other inner block is only their own function or their own
block and can not be used outside of their block.

1 - 10 10
Scope Operator
Int num1;
Void fun1(int num1)

 A local scope overrides the {


global scope //….. = 2;
int num1
 The global num1 is
}

inaccessible inside fun1(), void fun1(int num1)


because it is overridden by the {
local num1 parameter //…
 This problem is overcome num1=33;
using the scope operator ‘::’ cout<<num1; /* the output will be 33 */
which takes a global entity as cout<<::num1; /*the output will be 2
argument. which is the global */
if(::num1 != 0)//refers to global num1
1 - 11 11
//…
12

Inline Function

 DEFINITION:
In C++,the functions that are not actually
called, rather their code is expanded in line at the point of
each invocation such functions are called as inline functions.

1 - 12
13

SYNTAX
prototype fun_name( ); //function declaration
main( )
{
--------------------------
fun_name( ); //function call
}
inline prototype fun_name( );
//function definition
{
-------
}
1 - 13
14

WHY THERE IS A NEED OF INLINE


FUNCTIONS?

 A significant amount of overhead is generated by calling


and return mechanism of function.

 While calling the function arguments are pushed onto the


stack and saved on various registers and restore when
function returns , this will take more time to run.

 If we expand a function code inline then function call


produce faster run times.

1 - 14
15
SOME IMPORTANT POINTS
1.Inline function process is similar to using a macro.

2.Inline is actually just a request, not a command.

3.By marking it as inline, you can put a function definition in a


header file.

1 - 15
16

When to use ?

 Function can be made as inline as per programmer need.


Some useful recommendation are mentioned below-

1. Use inline function when performance is needed.


2. Use inline function over macros.
3. Prefer to use inline keyword outside the class with the
function definition to hide implementation details.

1 - 16
17

Consider the following example

int sum(int a, int b)


{
return a + b;
}
void print_sum()
{
int r = sum(5,6);
printf("%d\n", r);
}

1 - 17
18

If you declare your function as inline:


inline int sum(int a, int b)
{
return a + b;
}
 The compiler will replace the actual function call to the actual

body of your function, thus, the resulting binary will have


something like:
void print sum()
{
int r = 5 + 6;
printf("%d\n", r);
1 - 18
19

Program
#include <iostream>
using namespace std;
inline int sqr (int x) //defined function as inlined
{
int y;
y = x * x;
return y;
}
int main()
{
int a =3, b; // declaration of variables
b = sqr(a); //function call
cout <<b;
return 0;
}

1 - 19
20

Program
#include <iostream.h>
using namespace std;
inline int Max(int x, int y) //defined function as inlined
{
return (x > y)? x : y;
}
int main( ) // Main function for the program
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
1 - 20
21

 When the above code is compiled and executed, it produces


the following result :

Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010

1 - 21
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
inline double cube( const double s ) {
return s * s * s; }
int main() {
double side;
for ( int k = 1; k < 4; k++ ) {
cout << "Enter the side length of your cube: ";
cin >> side;
cout << "Volume of cube with side "
<< side << " is " << cube( side ) << endl;
} // end for
return 0;
} // end function main
1 - 22
23

Function Vs Inline Function

 In many places we create the functions for small


work/functionality which contain simple and less number of
executable instruction.

 Imagine their calling overhead each time they are being


called by callers.

1 - 23
24

 When a normal function call instruction is encountered:


 the program stores the memory address of the instructions
immediately following the function call statement,
 loads the function being called into the memory,
 copies argument values,
 jumps to the memory location of the called function,
 executes the function codes,
 stores the return value of the function, and
 then jumps back to the address of the instruction that was saved
just before executing the called function.
 Too much run time overhead.

1 - 24
25

 The C++ inline function provides an alternative. With inline


keyword:
 the compiler replaces the function call statement with the
function code itself (process called expansion) and then
 compiles the entire code.
 Thus, with inline functions, the compiler does not have to jump
to another location to execute the function, and then jump back
as the code of the called function is already available to the
calling program.

1 - 25
26

SOME OF THE SITUATION WHERE INLINE


EXPANSION MAY NOT WORK
 If the function code is large.

 If the function is recursive function .

 If the function contains static variables.

 For function returning values, if a loop, a switch , or a goto


exists
1 - 26
Function Overloading
 In C++, two or more functions can share the same name as
long as their parameter declarations are different.
 What is overloading?

 Overloading means assigning multiple meanings to a function


name or operator symbol
 It allows multiple definitions of a function with the same name,
but different signatures.
The key to function overloading is a function’s argument list.

 A function’s argument list is known as its signature.

 Function overloading allows functions that conceptually perform the

same task on objects of different types to be given the same name.

1 - 27
Function Overloading
Signatures

 C++ supports
 Function overloading
 Operator overloading

1 - 28
Function Overloading
 Two or more functions can have
the same name but different
parameters
 Example:
float max(float a, float b)
int max(int a, int b)
{
{
if(a>=b)
if(a>=b)
return a;
return a;
else
else
return b;
return b;
}
}

1 - 29
Overloading Function Overloading Call resolution

 Overloaded function call resolution is done by compiler during


compilation
 The function signature determines which definition is used
 a Function signature consists of:
 Parameter types and number of parameters supplied to a
function
 a Function return type is not part of function signature and is
not used in function call resolution

1 - 30
Overloading Function Overloading Call resolution

void sum(int, int);


void sum(int x, int y)
void sum(double, double);
{
void sum(char, char);
cout << x+y;
void main()
}
{
void sum(double x, double y)
int a=10,b=20; {
double c=7.52,d=8.14; cout << x+y;
char e=‘a’, f=‘b’; }
sum(a, b); //calls sum(int x, int y) void sum(char x, char y)
sum(c, d); //calls sum(double x,double {
y) cout << x+y;
sum(e, f); //calls sum(char x, char y) }
}
1 - 31
1
Outline
2 // Using overloaded functions
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int square( int x ) { return x * x; }
9
10 double square( double y ) { return y * y; }
11
12 int main()
13 {
14 cout << "The square of integer 7 is " << square( 7 )
15 << "\nThe square of double 7.5 is " << square( 7.5 )
16 << endl;
17
18 return 0;
19 } // end function main
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Friend Function

 If a function is defined as a friend function then, the


private and protected data of class can be accessed from
that function.
 The compiler knows a given function is a friend function

by its keyword friend.


 The declaration of friend function should be made inside

the body of class (can be anywhere inside class either in


private or public section).

1 - 33 33
Outline
// using friend function
#include <iostream>
using namespace std;
class Distance
{
private:
int meter;
public:
Distance(): meter(0){ }
friend int func(Distance); //friend function
};
int func(Distance d) //function definition
{
d.meter=5; //accessing private data from non-member function
return d.meter;
}
int main()
{
Distance D; //D is object type of Class
cout<<"Distace: "<<func(D);
return 0;
}
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Function Templates

 Function templates
 Compact way to make overloaded functions
 Keyword template
 Keyword class or typename before every formal type parameter (built in or
user defined)
template < class T > //or template< typename T >
T square( T value1)
{
return value1 * value1;
}
 T replaced by type parameter in function call
int x;
int y = square(x);
 If int parameter, all T's become ints
 Can use float, double, long...

1 - 35
1 Outline
2 // Using a function template
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 template < class T >
10 T maximum( T value1, T value2, T value3 )
11 {
12 T max = value1;
13
14 if ( value2 > max )
15 max = value2;
16
17 if ( value3 > max )
18 max = value3;
19
20 return max;
21 } // end function template maximum
22

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
23 int main() Outline
24 {
25 int int1, int2, int3;
26
27 cout << "Input three integer values: ";
28 cin >> int1 >> int2 >> int3;
29 cout << "The maximum integer value is: "
30 << maximum( int1, int2, int3 ); // int version
31
32 double double1, double2, double3;
33
34 cout << "\nInput three double values: ";
35 cin >> double1 >> double2 >> double3;
36 cout << "The maximum double value is: "
37 << maximum( double1, double2, double3 ); // double version
38
39 char char1, char2, char3;
40
41 cout << "\nInput three characters: ";
42 cin >> char1 >> char2 >> char3;
43 cout << "The maximum character value is: "
44 << maximum( char1, char2, char3 ) // char version
45 << endl;
46
47 return 0;
48 } // end function main

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Outline

Input three integer values: 1 2 3


The maximum integer value is: 3
Input three double values: 3.3 2.2 1.1
The maximum double value is: 3.3
Input three characters: A C B
The maximum character value is: C

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

You might also like