0% found this document useful (0 votes)
107 views34 pages

Unit-4.2 PPT Notes

The document discusses C++ functions including library functions, user-defined functions, and different ways functions can be called and defined. Some key points: 1) Functions allow programs to be divided into reusable and modular pieces of code. 2) Library functions are predefined while user-defined functions are created by the user. 3) Functions can be called by value where arguments are copied or by reference where the address is passed. 4) Functions can be defined with or without parameters and return values. They provide reusability and modularity.

Uploaded by

shivam sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views34 pages

Unit-4.2 PPT Notes

The document discusses C++ functions including library functions, user-defined functions, and different ways functions can be called and defined. Some key points: 1) Functions allow programs to be divided into reusable and modular pieces of code. 2) Library functions are predefined while user-defined functions are created by the user. 3) Functions can be called by value where arguments are copied or by reference where the address is passed. 4) Functions can be defined with or without parameters and return values. They provide reusability and modularity.

Uploaded by

shivam sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Object Oriented Techniques

Unit 4
C++ Functions

1
Functions
 A function is said to be a set of instructions that can perform a specific task. It will
reduce the size of the program by calling and using them at different places in the
program. The advantages are: Re- usability, modularity, overall programming
simplicity. Functions are classified into library functions and user-defined
functions.

 Library Functions

 User-Defined Functions

2
Advantages of functions:
 Functions are like building blocks
 They allow complicated programs to be divided into manageable pieces
A programmer can focus on just that part of the program and construct it, debug
it, and perfect it
 Different people can work on different functions simultaneously
 Can be re-used (even in different programs)
 Enhance program readability

3
Library Functions (predefined) functions )
 The functions that are already available in the C++ library are called Library
functions. Some important categories of library functions are : Input/Output
functions (iostream.h), Mathematical functions (Math.h), String handling functions
(String.h), Console input/output functions (conio.h) and Manipulator functions
(iomanip.h).
 Some example of the predefined mathematical functions are:
sqrt(x)
pow(x, y)
floor(x)

4
Predefined Functions
(continued)

5
sample run:

6
User-Defined Functions
 A function defined by the user is called as user-defined function.
 The advantage of user-defined function is that the complexity of a program is
reduced and the errors can be traced easily.
 Function Prototyping (or declaration): The prototype describes the function interface
to the compiler by giving details such as the number and type of arguments and the
type of return values.
 Function Definition: Function definition defines the operations of a function which is
already declared. When the function definition comes before the main() function, we
need not declare it.
 Function call : The process of calling a function for execution is known as function
call. Any user defined function can call any other function. There are two types of
function call: Call by value and Call by reference

7
1. Function with parameters (arguments) and without return
values. #include <iostream.h>
#include <conio.h>
void main( )
{
int a=10,
b=10;
void add(int,int);
clrscr();
add(a,b);
getch();
}
void add(int x, int y)
{

} cout<< x+y;
8
2. Function with parameters (arguments) and with a return
value. #include <iostream.h>
#include <conio.h>
void main( )
{
int a=10,
b=10;
int add(int,int);
clrscr();
cout <<
add(a,b);
getch();
}
int add(int x, int y)
{
} 9
return(x+y);
3. Function without parameter (argument) and with a return value.
#include <iostream.h>
#include <conio.h>
void main( )
{
int add();
clrscr();
cout << add();
getch();
}
int add()
{
int x=10, y=10;
return(x+y);
}
10
4. Function without parameter (argument) and without a return value.
#include <iostream.h>
#include <conio.h>
void main( )
{
void add();
clrscr();
add();
getch();
}
void add()
{
int x=10, y=10;
cout << (x+y);
}
11
Parameter Passing in
Functions
 Call By Value :
When a function is called by supplying values as parameters (arguments), it is called
Call By Value. The values placed in the actual parameters are copied into the formal
parameters. So any changes made to the formal parameters do not affect the actual
parameters.
 Call By Reference:
When we pass parameters (arguments) by reference, the formal parameters in the
called function become aliases to the actual parameters in the calling function. So any
change made in the formal parameters affect the original value.

12
Call by value Example
#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}
Call by reference Example
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}
Difference between call by value and call by reference in C++

No. Call by value Call by reference


1 A copy of value is passed to An address of value is passed to
the function the function

2 Changes made inside the Changes made inside the


function is not reflected on function is reflected outside the
other functions function also

3 Actual and formal Actual and formal arguments


arguments will be created will be created in same memory
in different memory location location
Return By Reference:
 A function can also return a reference.
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 and y (and
not the value). Then 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 assigns -1 to a if it is larger, otherwise -1 to b.

17
Inline Function
 One of the objectives of using functions in a program is to save some memory
space, which becomes appreciable when a function is likely to be called many
times.
 Every time a function is called, it takes a lot of extra time is executing a series of
instructions for tasks such as jumping to the functions, saving registers, pushing
arguments into stack, and returning to the calling function.
 eliminate the cost of calls to small functions, C++ proposes a new feature called
 inline function.
 When the inline function is called whole code of the inline function gets inserted or
substituted at the point of inline function call.
 This substitution is performed by the C++ compiler at compile time.

18
Point to be noted for Inline function

Compiler may not perform inlining in such circumstances like:

1) If a function contains a loop. (for, while, do-while)

2) If a function contains static variables.

3) If a function is recursive.

4) If a function contains switch or goto statement.


Inline functions provide following advantages:
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when function is
called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context specific
optimization on the body of function. Such optimizations are not possible for normal
function calls. Other optimizations can be obtained by considering the flows of
calling context and the called context.
5) Inline function may be useful (if it is small) for embedded systems because inline
can yield less code than the function call preamble and return.
Inline function disadvantages:
1) The added variables from the inlined function consumes additional registers, After in-lining function if variables
number which are going to use register increases than they may create overhead on register variable resource
utilization. This means that when inline function body is substituted at the point of function call, total number of
variables used by the function also gets inserted. So the number of register going to be used for the variables will also
get increased. So if after function inlining variable numbers increase drastically then it would surely cause an
overhead on register utilization.
2) If you use too many inline functions then the size of the binary executable file will be large, because of the
duplication of same code.
3) Too much inlining can also reduce your instruction cache hit rate, thus reducing the speed of instruction fetch from
that of cache memory to that of primary memory.
4) Inline function may increase compile time overhead if someone changes the code inside the inline function then all
the calling location has to be recompiled because compiler would require to replace all the code once again to reflect
the changes, otherwise it will continue with old functionality.
5) Inline functions may not be useful for many embedded systems. Because in embedded systems code size is more
important than speed.
6) Inline functions might cause thrashing because inlining might increase size of the binary executable file. Thrashing
in memory causes performance of computer to degrade.
Syntax for Inline Function

inline return-type function-name(parameters)

// function code

}
Inline Function Example

#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
} //Output: The cube of 3 is: 27
Inline function and classes:

It is also possible to define the inline function inside the class.


In fact, all the functions defined inside the class are implicitly inline.
Thus, all the restrictions of inline functions are also applied here.
If you need to explicitly declare inline function in the class then just declare the function
inside the class and define it outside the class using inline keyword.

class S
{
public:
int square(int s); // declare the function
};

inline int S::square(int s) // use inline prefix


{

}
Macros
 Macros are a piece of code in a program which is given some name. Whenever this name is
encountered by the compiler the compiler replaces the name with the actual piece of code.
The ‘#define’ directive is used to define a macro. Let us now understand the macro definition
with the help of a program:
 There is no semi-colon(‘;’) at the end of macro definition. Macro definitions do not need a
semi-colon to end.
#include <iostream>
// macro definition
#define LIMIT 5 int
main()
{
for (int i = 0; i <
LIMIT; i++)
• {
std::cout
<< i <<
"\n";
25
}
Macros with arguments
 We can also pass arguments to macros. Macros defined with arguments works
similarly as functions.
#include <iostream>
// macro with parameter
#define AREA(l, b) (l *
b) int main()
{
int l1 = 10, l2 = 5,
area; area = AREA(l1,
l2);
std::cout << "Area of rectangle is: " <<
area; return 0;
}

26
Difference between Inline and MACRO
BASIS FOR
INLINE MACRO
COMPARIS
ON
Basic Inline functions are parsed by the compiler. Macros are expanded by the
preprocessor.
Syntax inline return_type funct_name ( parameters ){ . . . } #define macro_name char_sequence

Keywords Used inline #define


It is always defined at the start
Defined It can be defined inside or outside the class.
of the program.
It evaluates the argument each time it
Evaluation It evaluates the argument only once.
is used in the code.
Expansion The compiler may not inline and expand all the Macros are always expanded.
functions.
27
Difference between Inline and MACRO
BASIS FOR
INLINE MACRO
COMPARISO
N
The short functions, defined inside the
Automation Macros should be defined specifically.
class are automatically made onto
inline functions.
An inline member function can access the data Macros can never be the members of the
Accessing
members of the class. class and can not access the data members
of the class.
Definition of inline function terminates with
Termination Definition of macro terminates with the new
the curly brackets at the end of the inline
line.
function.
Debugging is easy for an inline function as error Debugging becomes difficult for macros as
Debugging
checking is done during compilation. error checking does not occur during
compilation.
An inline function binds all the statements in the
A macro faces the binding problem if it has
Binding body of the function very well as the body of the
more than one statement, as it has no
function start and ends with the curly brackets.
termination symbol.
28
Difference between Inline function and Normal
function in C++
It is a function that provides modularity to
It is expanded inline when it is invoked.
1 the program.

It is generally used to decrease the execution time of It is generally used to improve the reusability
2.
the program. of code and make it more maintainable.
It is basically a group of statements that
It is basically a function that is used when functions are
3. performs a particular task. It is used when
small and called very often.
functions are big.
It does not require any keyword in its
4. It requires ‘inline‘ keyword in its declaration.
declaration.
It generally executes much faster as compared to It generally executes slower than inline
5.
normal functions. function for small size function.
In this, the body of the function is stored in
In this, the body of functions is copied to every context the storage device and when that particular
6. where it is used that in turn reduces the time of function is called every time, then CPU has to
searching the body in the storage device or hard disk. load the body from hard disk to RAM for
execution.
Difference between Inline function and Normal
function in C++
The compiler always places a copy of the code
7. of that function at each point where the It does not provide such a type of
function is called at compile time. functionality.
When the number of line codes is real
8. It generally includes only 2–3-line codes. massive I.e., normal functions contain
much code as per need.
9.
It is a little harder to understand and test as It is much easier to understand and test
compared to normal function. as compared to the inline function.
10.
Functions that are present inside a class are Functions that are present outside class
implicitly inline. are considered normal functions.
11.
Too many inline functions affect file size after Too many normal functions do not
compilation as it duplicates the same code. affect file size after compilation.
Function Overloading
 Provides the mechanism by which C++ achieves one type of polymorphism
(called compile-time polymorphism).
 Two or more functions can share the same name as long as either
• The type of their arguments differs, or
• The number of their arguments differs, or
• Both of the above
 The compiler will automatically select the correct version.
 The return type alone is not a sufficient difference to allow function overloading.

31
Function Overloading
(continued)
• Correct function overloading:

• Syntax error:

32
Default Arguments
 In C++, A default argument is a value provided in a function declaration that is
automatically assigned by the compiler if the caller of the function doesn’t provide a
value for the argument with a default value.

 Example:

33
Thank
You
34

You might also like