Function Overloading
Function Overloading
Definition: Function overloading means two or more function have same name but
differ in the number of arguments or data types of arguments ie function name is
overloaded.
Function overloading is also called as Compile time polymorphism.
Ex.
int area(int r);
int area(int b, int h);
void cal(float a, float b);
void cal(float a, float b, float c);
//Write a program to find area of circle and triangle using function overloading.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class funoverload
{
private: int r,b,h;
float carea, tarea;
public: void area(int r);
void area(int b, int h);
};
void funoverload :: area(int r)
{
carea = 3.142*r*r;
cout<<"The area of a circle is = "<<carea<<endl;
}
void funoverload :: area(int b, int h)
{
tarea = 0.5*b*h;
cout<<"The triangle area is ="<<tarea;
}
void main()
{
funoverload p;
clrscr();
p.area(5);
p.area(4,7);
getch();
}
//Write a program to perform addition using function overloading.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class arith
{
private: int a,b,isum;
float fsum;
public: void add(int a, int b);
void add(float a, float b, float c);
};
void arith :: add(int a, int b)
{
isum = a + b;
cout<<"The addition of two numbers="<<isum<<endl;
}
void arith :: add(float a, float b,float c)
{
fsum = a + b + c;
cout<<"The addition of three numbers ="<<fsum;
}
void main()
{
arith h;
clrscr();
h.add(5,8);
h.add(2.5, 7.8,4.5);
getch();
}
Inline Function
The inline function is a short function where compiler replaces a function call
with the body of the function.
➢ The keyword inline is used to define inline function
➢ The compiler replaces the function call statement with the function code itself and
then complies the entire code
➢ It should be defined before all functions that call it
➢ They run little faster than normal function.
Friend Function
A friend function is a non-member function that is a friend of a class.
OR
It is a function which has authorization to access the private and protected members
of a class though it is not a member of the class.
➢ A friend function is declared within a class
➢ It is declared with prefix friend
➢ It can access public data members
Syntax:
class class-name
{
private:
public: friend return-type-specifier function-name(arguments);
}
❖ While defining a friend function outside the class it does not required either
keyword friend or scope resolution operator (:: )
❖ It has full access right to private and protected members of the class
❖ Unlike member function, it cannot access the member name directly and has to
use an object name and dot membership operator with each member name(
data member)
Ex. S.a
where
s→ object name of a class
a→ private data member
❖ IMP
Usually, friend function has the object as arguments
Ex.
add(p)→Inside main() declaration
add→ function-name
p→ Object of a class inside main() function