Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 14

FUNCTION OVERLOADING

PDPU
FUNCTION OVERLOADING …
 Known as function polymorphism also.
 Overloading means using same thing for
different purposes.
 Feature of C++ and not C.
 Using the concept, we can design a family of
functions with one function name but with
different argument lists.
 Compile-Time Polymorphism
FUNCTION OVERLOADING …
 The function would perform different
operations depending on the argument list in
the function call.
 The correct function to be invoked is
determined by checking the number and type
of the arguments and not from what function
returns.
Function Overloading Example

void main() void add( int a, int b)


{ {
void add( int, int); cout << a + b;
void add( int, int, int); }
add(50,70);
add(50,70,90); void add( int a, int b, int c)
} {
cout << a + b + c;
}
Example … Creating object in main( )
and calling functions …

void main()
{
clrscr();
numbers x;
x.add();
x.add(50,70);
getch();
Please go through
}; the program
“exovrld1.cpp”
Example …
defining class numbers …

class numbers
{
private:
int a , b;
public:
void add (void);
void add (int, int);
};
Example …
defining member functions …

void numbers :: add()


{
cin >> a >> b; cout << a + b << endl;
}
void numbers :: add (int a, int b)
{
numbers::a = a; numbers::b = b;
cout << numbers::a + numbers::b << endl;
}
Another Example … Creating objects
in main() and calling Functions…

void main()
{
shape square, rect, circle;
square.area(5);
rect.area(10,20);
circle.area(10.00);
getch();
Please go through
}; the program
“exovrld2.cpp”
Example …
Defining Class shape…

class shape
{
private:
int length, breadth; float a, radius;
public:
void area (int); // area of a square.
void area (int, int); // area of a rectangle.
void area (double); // area of a circle.
};
Example …
Defining member functions…

void shape :: area (int l)


{
length = l;
a = length * length;
cout << "Area of a square = " << a << endl;
}
Example …
Defining member functions…

void shape :: area( int l, int b)


{
length = l;
breadth = b;
a = length * breadth;
cout << "Area of a Rectangle = " << a << endl;
}
Example …
Defining member functions…

void shape :: area (double r)


{
radius = r;
a = 22.0 / 7 * radius * radius ;
cout << "Area of a Circle = " << a << endl;
}
Think about this…
What happens if …

 … we write square.area(5.0);
 … we write circle.area(5);
 … we write another function called
void shape :: area (float) ;
 … we write another function called
int shape :: area (int , int);
SUMMARY …

 Overloading means function polymorphism.


 Overloading means using same name of
function to carry out different types of work.
 The differentiation is in terms of no. of
arguments and type of arguments and not in
terms of what function returns.

You might also like