Tuesday 13 November 2012

Inline functions and functions overloadings



Function overloading:
Overloading refers to the use of same thing for different purposes. Function overloading means, we can use the same function name to create functions that perform a variety of different tasks. This is called function polymorphism or compile-time polymorphism in OOP. Another is run time polymorphism which we’ll discuss later 
The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type (return type). 


#include<iostream.h>  
float area(int); 
int area(int,int); 
void main() 
int r; 
cout<<”Enter radius of a circle”; 
cin>>r; 
float a=area(r); 
cout<<”Area of circle is “<<a; 
int l,b,A; 
cout<<”Enter length and breadth of rectangle”; 
cin>>l>>b; 
A=area(l,b); 
cout<<”Area of rectangle is “<<A; 
float area(int R) 
{
 return(3.14*R*R); } 
int area(int L, int B) 
{
 return(L*B); 





Inline function:

Function in a program is to save memory space which becomes appreciable when a function is likely to be called many times.
However every time a function is called, it takes 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.
So when function is small it is worthless to spend so much extra time in such tasks in cost of saving comparatively small space.
To eliminate the cost of calls to small functions, C++ proposes a new feature called inline function.
An inline function is a function that is expanded in line when it is invoked.
Compiler replaces the function call with the corresponding function code.
inline is a request not a command.
The benefit of speed of inline functions reduces as the function grows in size.
So the compiler may ignore the request in some situations.

Few of them:
Function containing loops, switch, goto.
Functions with recursion
Containing static variable.



#include<iostream.h>
inline int add(int, int);
void main()
{
int a,b;
cout<<”Enter two numbers”;
cin>>a>>b;
int sum=add(a, b);
cout<<”Sum is “<<sum;
}
int add(int x, int y)
 return(x+y);
}

No comments:

Post a Comment