Вы находитесь на странице: 1из 106


What is function????

Function is a self contained block of

statements that perform a coherent task
of some kind.
In C++ program an object have data
collection of functions.
main( ) is also a function.
Types of Functions.

Library functions
These are the in- -built functions of C++ library.
These are already defined in header files.
e.g. getch() is a function which is used to get a
char from keyboard. It is defined in conio.h file
User defined functions.
Programmer can create their own function in C+
+ to perform specific task
a) Actual arguments:-the arguments of
calling function are actual arguments.
b) Formal arguments:-arguments of called
function are formal arguments.
c) Argument list:-means variable name
enclosed within the paranthesis.they
must be separated by comma
d) Return value:-it is the outcome of the
function. the result obtained by the
function is sent back to the calling
function through the return statement.
Why use function?
Writing functions avoids rewriting of the
same code again and again in the
Using function large programs can be
reduced to smaller ones. It is easy to
debug and find out the errors in it.
Using a function it becomes easier to
write program to keep track of what they
are doing.
Function Declaration
ret_type func_name(data_type par1,data_type par2);

Function Defination
ret_type func_name(data_type
par1,data_type par2)

Function Call
func_name(data_type par1,data_type par2);
Function prototype

A prototype statement helps the compiler

to check the return type and arguments
type of the function.
A prototype function consist of the
functions return type, name and
argument list.
int sum( int x, int y);
using namespace std;
void sum(int, int); // function declaration
int main()
int a, b;
cout<<enter the two no;
sum(a,b); // function calling
return 0;
void sum( int x, int y)// function definition
{ int c;
cout<< sum is<<c;
using namespace std;
int sum(int x, int y);
int main()
int a=10,b=20;
int c=sum(a,b); /*actual arguments
cout<<sum is << c;
return 0;
int sum(int x, int y) /*formal arguments
int s;
return s; /*return value
Inline Functions
Each time you call a function in a C++
program, the computer must do the
Remember where to return when the function eventually ends

Provide memory for the functions variables

Provide memory for any value returned by the function

Pass control to the function

Pass control back to the calling program

This extra activity constitutes the overhead,

involved in calling a function.
Solution to this is to replace each function call with
the necessary code instead of making function.
Inline function is a function which gets expanded
inline at each point in the program where it is
In other words inline functions are those functions
whose function body is inserted in place of the
function call during the compilation process.
inline ret_type func_name(parameter_list)
function body
Normal function

Inline function
using namespace std;
inline int max(int x,int y)
return (x>y?x:y);
int main()
int m=10,n=25;
int a,b;
cout<<greatest is<<a;
cout<<greates of m=<<m<< and n=<<n
<<is <<b;
return 0;
Output :
Greatest is 8
Greatest of m=10 and n=25 is 25
An inline function is a small function with
no calling overhead
Overhead is avoided because program
control never transfers to the function
A copy of the function statements is placed
directly into the compiled calling program
The inline function appears prior to the
main(), which calls it
Any inline function must precede any
function that calls it, which eliminates the
need for prototyping in the calling function

All functions that uses the inline function must be

recompiled if any changes are made to the inline
Although inline function reduces the execution
time. It increases the size of the executable file as
multiple copies of the inline functions body are
inserted in the programs. So it is always
recommended to use inline functions for small
frequently used functions.
The definition of inline function should appear
before the function call.
Static Data Members
A data member of a class can be qualified as static. A static
member variable has certain special characteristics. These
It is initialized to zero when the first object of its class is
created. No other initialization is permitted.
Only one copy of that member is created for the entire class
and is shared by all the objects of that class, no matter how
many objects are created.
It is visible only within the class, but its lifetime is the entire
Static Data Members
The type and scope of each static member
variable must be defined outside the class

They are also known as class variables since

they are associated with the class itself rather
than with any class object.
#include<iostream> int main()
class item {
{ item a,b,c;
static int count;
int number; a.getcount();
public: b.getcount();
void getdata(int a) c.getcount();
number=a; a.getdata(100);
count++; b.getdata(200);
void getcount() c.getdata(300);
cout<<"after reading
cout<<"count="<<count; data";
} a.getcount();
}; b.getcount();
int item::count; c.getcount();
after reading data
Static Member Functions

The main usage of static function is when the programmer

wants to have a function which is accessible even when the
class is not instantiated.
Static member functions have a class scope and they do not
have access to the 'this' pointer of the class.
Static Member Functions
Static function is defined by using the keyword static before the
member function that is to be declared as static function.
static return_data_type function_name()
statement 1;
statement 2;
Static Member Functions
The functions declared static or static functions are accessed
using only the class name and the scope resolution operator,
unlike in normal member functions where these are not used.

A static member function can only access static member data,

of the class.
Static Member Functions
A non-static member function can be declared as virtual
but care must be taken not to declare a static member
function as virtual.

It is possible to declare a data member of a class as

static irrespective of it being a public or a private type in
class definition.
#include<iostream> int main()
class test {
{ test t1,t2;
int data; t1.setdata();
static int count; t2.setdata();
void setdata()
{ test::showcount()
data=++count; ;
void showdata() test t3;
{ t3.setdata();
cout<<"object number:
} test::showcount()
static void showcount() ;
"<<count<<endl; t1.showdata();
} t2.showdata();
}; t3.showdata();
return 0;
count: 2
count: 3
object number: 1
object number: 2
object number: 3
Categories of functions

A function with no parameter and no return value

A function with parameter and no return value
A function with parameter and return value
A function without parameter and return value
A function with no parameter and no return
Using namespace std;
void print(); /*func declaration
int main()
Cout<<no parameter and no return value;
print(); /*func calling
return 0;
void print() /*func defination
For(int i=1;i<=30;i++)
A function with no parameter and no return

There is no data transfer between calling

and called function
The function is only executed and nothing
is obtained
Such functions may be used to print
some messages, draw stars etc
A function with parameter and no
return value

using namespace std;
void mul(int,int);
int main()
int a=10,b=20;
mul(a,b); /*actual arguments
return 0;
void mul(int x, int y) /*formal arguments
int s;
Cout<<mul is << s;
A function with parameter and return
using namespace std;
int max(int,int);
int main()
int a=10,b=20,c;
Cout<<greatest no is <<c;
return 0;
int max(int x, int y)
A function without parameter and
return value
using namespace std;
int main()
int a=10,b=20;
int sum();
int c=sum(); /*actual arguments
cout<<sum is<< c;
return 0;
int sum() /*formal arguments
int x=10,y=30;
return(x+y); /*return value
Some important points

A function declaration,defination,and call must

match in number,type and order of actual and
formal arguments.
A function can b called from other function but a
function cannot be defined inside another function
Function defined and function call order can b
The actual arguments in a function can be
variables,constants,or expression where as formal
arguments must be variables
Default arguments is useful in situation where a
arguments has the same value in most function
When the desired value is different from the
default value,the desired value can be specified
explicity in a function call.
This changes the default value of the argument
to be overridden for the duration of function call.
If in the function call all the arguments are not
specified then the omitted arguments can take
default value by providing them in the function
using namespace std;

void sum(int a, int b=20);

int main()
return 0;

void sum(int a,int b)

int temp;
cout<<"sum ="<<temp;
Using Default Arguments
Two rules apply to default parameters:
If you assign a default value to any variable in a function prototypes parameter list,
then all parameters to the right of that variable also must have default values
If you omit any argument when you call a function that has default parameters, then
you also must leave out all arguments to the right of that argument
using namespace std;
float SI(float p,float r=5.5,float t=1.0); //function declaration
int main()
float k;
cout<<"Simple interest ="<<k<<endl;
cout<<"Simple interest ="<<k<<endl;
cout<<"Simple interest ="<<k<<endl;
return 0;
float SI(float p,float r,float t)
float si=(p*r*t)/100;
return si;
These are special stream functions that
change certain characteristics of input
and output.
The main advantage of using manipulator
functions is that they facilitate the
formatting of input and output stream.
To carry out the operations of these
manipulator functions the header file
<iomanip.h> must be included.
Following are the standard manipulators
normally used in the stream classes:


It is an output manipulator to generate a

next line character.

Used to convert the base of one numeric value into another

int main()
int value;
Cout<<enter number<<endl;
Cout<<decimal base <<setbase(10)<<value;
cout<<hexadecimal base<<setbase(16)<<value;
Cout<<octal base<<setbase(8)<<value;
Enter number 10
Decimal base 10
Hexadecimal base=a
Octal base 12
It is used to specify the minimum number of character position
on the output field a variable will consume.
int main()
int a=200,b=300;
return 0;
200 300
200 300
200 300
200 300
It is used to specify a different character to fill the unused field width of the
int main()
int a=200,b=300;
return 0;
It is used to control the number of digits of an
output stream display of a floating point
The default precision is 6
void main()
float a=5,b=3,c;
The word polymorphism is derived from
Greek word Poly which means many and
morphos which means forms.
Polymorphism can be defined as the
ability to use the same name for two or
more related but technically different
Overloading in C++

What is overloading
Overloading means assigning multiple
meanings to a function name or operator
It allows multiple definitions of a function with the
same name, but different signatures.
C++ supports
Function overloading
Operator overloading
Why is Overloading Useful?

Function overloading allows functions that

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

Operator overloading provides a convenient

notation for manipulating user-defined
objects with conventional operators.
Function Overloading
Is the process of using the same name for two or
more functions
Requires each redefinition of a function to use a
different function signature that is:
different types of parameters,
or sequence of parameters,
or number of parameters
Is used so that a programmer does not have to
remember multiple function names
Function Overloading

Two or more functions can have the same

name but different parameters
int max(int a, int b) float max(float a, float b)
{ {
if (a>= b) if (a>= b)
return a; return a;
else else
return b; return b;
} }
Overloading Function Call
Overloaded function call resolution is done by
compiler during compilation
The function signature determines which
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
and is not used in function call resolution
void sum(int,int);
void sum(double,double);
void sum(char,char);
int main()
int a=10,b=20 ;
Double c=7.52,d=8.14;
char e=a , f=b ;
sum(a,b); //calls sum(int x, int y)
sum(c,d); //calls sum (double x, double y)
sum(e,f); // calls sum(char x, char y)
return 0;

void sum(int x, int y)
cout<<\n sum of integers are<<x+y;

void sum(double x, double y)

cout<<\n sum of two floating no are<<x+y;

void sum(char x, char y)

cout<<\n sum of characters are<<x+y;
Sum of integers 30
sum of two floating no are 15.66
sum of characters are 195
void area(int x)
using namespace std;
void area(int);
cout<<area is<<x*x;
void area(int,int);
void area(int,int,int);
void area(int x,int y)
Int main()
cout<<area of rectangle=<<x*y;
int side=10,le=5,br=6,a=4,b=5,c=6;
void area(int x,int y,int z)
cout<<area of triangle<<x*y*z;
return 0;

The scope of a variable is the portion

of a program where the variable has
meaning (where it exists).
A global variable has global (unlimited)
A local variables scope is restricted to
the function that declares the variable.
A block variables scope is restricted to
the block in which the variable is
Understanding Scope

Some variables can be accessed throughout

an entire program, while others can be
accessed only in a limited part of the program

The scope of a variable defines where it can

be accessed in a program

To adequately understand scope, you must be

able to distinguish between local and global
Local variables

Parameters and variables declared inside

the definition of a function are local.
They only exist inside the function body.
Once the function returns, the variables
no longer exist!
Thats fine! We dont need them anymore!
Block Variables

You can also declare variables that exist

only within the body of a compound
statement (a block):
int foo;

Global variables

You can declare variables outside of any

function definition these variables are
global variables.
Any function can access/change global
Example: flag that indicates whether
debugging information should be printed.
Distinguishing Between Local
and Global Variables
Celebrity names are global because they are
known to people everywhere and always refer to
those same celebrities

Global variables are those that are known to all

functions in a program

Some named objects in your life are local

You might have a local co-worker whose name

takes precedence over, or overrides, a global one
A note about
Global vs. File scope
A variable declared outside of a function
is available everywhere, but only the
functions that follow it in the file know
about it.

The book talks about file scope, Im

calling it global scope.
Block Scope
int main(void) {
int y=10;

{ t o
t ex
int a = y; esn
cout << a << endl; a
r k !
ro o c
Er e bl
} th

cout << a << endl;

Friend Function

When we want our private data to be

shared by a non member function
Basically, we declare something as a
friend, you give it access to your private
data members.
Single functions or entire classes may be
declared as friends of a class.
Friend function
A Friend function is a non-member function of
the class that has been granted access to all private
members of the class.

We simply declare the function within the class by

a prefixing its declaration with keyword friend.

Function definition must not use keyword friend.

Definition of friend function is specified outside the

class body and is not treated as a part of the class.

The major difference b/w member function and

class ABC
friend void xyz(arguments);
Friend function characterstics

It is not in scope of class.

It cannot be called using object of that class.
It can be invoked like a normal function.
It should use a dot operator for accessing members.
It can be public or private.
It has objects as arguments.
Perhaps the most common use of friend functions is
overloading << and >> for I/O.
Friend Function definedinside
the class
class demo
int a;
void getdata();
friend void sample(demo abc)
class sample
int a;
int b;
void setval(){ a=25,b=40}
friend float mean(sample s);
float mean(sample s)
return (s.a+s.b)/2.0;
void main()
sample X;
Friend class

In previous section of class we declared

only one function as a friend of another
class. but it is possible that all member of
the one class can be friend of another
class. This is friend class.
class A class B
{ {
int x, y; int p,q;
public: public:
void setdata(int a,int void fun1(A ob)
b) {
{ p=ob.x;
x=a; q=ob.y;
y=b; }
} void fun2(A ob)
friend class B; {
class abc class xyz
{ {
int data; int data;
public: public:
void setvalue(int x) void setvalue(int x)
{ {
data=x; data=x;
} }
void display() void display()
{ {
cout<<data; cout<<data;
} }
friend void sum (abc,xyz); friend void sum(abc,xyz);

}; };
Argument passing techniques

Pass By Value
Pass By Pointer\address
Pass By reference
Call By Value

It is a default mechanism for argument passing.

When an argument is passed by value then the
copy of argument is made know as formal
arguments which is stored at separate memory
Any changes made in the formal argument are
not reflected back to actual argument, rather
they remain local to the block which are lost
once the control is returned back to calling
int swap(int,int); void swap(int x,int
int main() y)
{ {
int a=10,b=20; int z;
cout<<before function calling<<a<<b;
cout<<after function calling<<a<<b; x=y;
return 0; y=z;
before function calling a=10 b=20
value of x=20 and y= 10
after function calling a=10 b=20
Call By pointer/address
In this instead of passing value, address are
Here formal arguments are pointers to the actual
Hence change made in the argument are
The address of arguments is passed by preceding
the address operator(&) with the name of the
variable whose value you want to modify.
The formal arguments are processed by asterisk (*)
which acts as a pointer variable to store the
addresses of the actual arguments
int swap(int*,int*); void swap(int *x,int
int main() *y)
{ {
int a=10,b=25; int z;
cout<<before function calling<<a<<b;
cout<<after function calling<<a<<b; *x=*y;
return 0; *y=z;

before function calling a= 10 b= 25

after function calling a=25 b= 10

Using Reference Variables
with Functions

To create a second name for a variable

in a program, you can generate an alias,
or an alternate name

In C++ a variable that acts as an alias

for another variable is called a reference
variable, or simply a reference
Declaring Reference Variables

You declare a reference variable by placing a

type and an ampersand in front of a variable
name, as in double &cash; and assigning
another variable of the same type to the
reference variable

double Money;

double &cash = Money;

A reference variable refers to the same

memory address as does a variable, and a
pointer holds the memory address of a variable
int swap(int&,int&); void swap(int
int main() &x,int &y)
{ {
int a=10,b=25; int z;
cout<<before function calling<<a<<b;
cout<<after function calling<<a<<b; x=y;
return 0; y=z;

before function calling a= 10 b= 25

after function calling a=25 b= 10

Value 10 10
modified value 20 20
Declaring Reference Variables

There are two differences between reference

variables and pointers:
Pointers are more flexible
Reference variables are easier to use
You assign a value to a pointer by inserting an
ampersand in front of the name of the variable
whose address you want to store in the pointer
It shows that when you want to use the value
stored in the pointer, you must use the asterisk
to dereference the pointer, or use the value to
which it points, instead of the address it holds
Call by valueThis method copies the
actual value of an argument into the
formal parameter of the function. In this
case, changes made to the parameter
inside the function have no effect on the
. Call by pointerThis method copies the
address of an argument into the formal
parameter. Inside the function, the
address is used to access the actual
argument used in the call. This means
that changes made to the parameter
affect the argument.
Call by referenceThis method copies the
reference of an argument into the formal
parameter. Inside the function, the
reference is used to access the actual
argument used in the call. This means
that changes made to the parameter
affect the argument.
When function call itself repeatedly ,until
some specified condition is met then this
process is called recursion.
It is useful for writing repetitive problems
where each action is stated in terms of
previous result.
The need of recursion arises if logic of the
problem is such that the solution of the
problem depends upon the repetition of
certain set of statements with different
input values an with a condition.
Two basic requirements for recursion :
1. The function must call itself again and
2. It must have an exit condition.
int main()
{ int factorial(int a)
int factorial (int); {
int x,fact; int b;
cout<<enter a number=; if(a==1)

cin>>x; return (1);

cout<<\nfactorial of<<x<<=<<fact;
return 0;
return (b);
} }
Enter a number=3
Factorial0f 3=6
Stack representation

. 3*2*fact(1)
3*fact(2) 3*fact(2)
fact(3) fact(3)


Fibonacci using recursion
int main()
int fib(int m)
int fib(int);
int n;
if(m==1|| m==2)
cout<<enter the number of terms=;
for(int i=1;i<=n;i++)
cout<<fib(i)<< ;
return 0;
Advantages of recursion
1. It make program code compact which is
easier to write and understand.
2. It is used with the data structures such
as linklist,stack,queues etc.
3. It is useful if a solution to a problem is in
repetitive form.
4. The compact code in a recursion
simplifies the compilation as less
number of lines need to be compiled.

1. Consume more storage space as

recursion calls and automatic variables
are stored in a stack.
2. It is less efficient in comparison to normal
program in case of speed and execution
3. Special care need to be taken for stopping
condition in a recursion function
4. If the recursion calls are not checked ,the
computer may run out of memory.