11th Computer Science 12th Computer Science BCA CBSE JAC JAC

Method / Function overloading in C++

Method / Function overloading in C++
Written by AIPS

Method / Function overloading means more than one functions with same name with different arguments for different purpose in a program.

Method / Function overloading is an example of polymorphism.

Using no argument no return value function overloading can’t be done.

Example

void area(int); // to find area of square

void area(int,int); //to find area of rectangle

void area(float); // to find area of circle

Q.Write a program to find area of Square,Rectangle, and Circle using function overloading. (compile time)

#include<iostream.h>
#include<conio.h>
void area(int); // for area of square
void area(int,int); // for area of rectangle
void area(float);  // for area of circle
void main()  
{
clrscr();
int s,l,b;
float r;
s=5;
l=6;
b=4;
r=5;
area(s);
area(l,b);
area(r);
getch();
}
void area(int x)
{
cout<<”Area of square=”<<(x*x);
}
void area(int x , int y)
{
cout<<”\nArea of rectangle=”<<(x*y);
}
void area(float x)
{
cout<<”\nArea of circle=”<<(3.14*x*x);
}

Output

Area of square=25

Area of rectangle=24

Area of circle=78.5

Q.Write a program to find area of Square,Rectangle, and Circle using function overloading. (Run time)

#include<iostream.h>
#include<conio.h>
void area(int); // for area of square
void area(int,int); // for area of rectangle
void area(float);  // for area of circle
void main()  
{
clrscr();
int s,l,b;
float r;
cout<<”Enter value of side,length,breadth, and radius=”;
cin>>s>>l>>b>>r;
area(s);
area(l,b);
area(r);
getch();
}
void area(int x)
{
cout<<”Area of square=”<<(x*x);
}
void area(int x , int y)
{
cout<<”Area of rectangle=”<<(x*y);
}
void area(float x)
{
cout<<”\nArea of circle=”<<(3.14*x*x);
}

output

Enter value of side,length,breadth, and radius=5

6

4

5

Area of square=25

Area of rectangle=24

Area of circle=78.5

Note :-

Method / Function Overriding :-

When base class and derived class contains the method of same signature then this term is known as method overriding.

Same signature means every this is same i. Method name, arguments, types, etc.

when we call the method using object of derived class then method of base class is overridden.

example.

class nips

{

public:

void show(int x,int y)

{

…………………

}

};

class gla: public nips

{

public:

void show(int x,int y)

{

……………………

}

}

This topic will be discussed after Inheritance…… …

About the author

AIPS

Leave a Comment