C++ program to implement function overloading

Description


This program implements function overloading in c++. Function overloading can be used for implementing polymorphism. Function overloading refers to the use of multiple functions with the same name but with different parameters in the same class. This program two functions add(), one without parameters and other with two parameters. The function call s.add(); calls the first function and the function call s.add(p,q); calls the second function.

Program


//function overloading

#include<iostream.h>

#include<conio.h>

class sample

{

int a,b,c;

public:

void add()

{

a=10;

b=5;

c=a+b;

cout<<"\nc= "<<c;

}

void add(int x,int y)

{

a=x;

b=y;

c=a+b;

cout<<"\nC= "<<c;

}

};

void main()

{

int ch,p,q;

sample s;

cout<<"\n1.Add without parameter\n2.Add with parameter\n3.Exit";

cout<<"\nEnter your choice: ";

cin>>ch;

while(ch!=3)

{

if(ch==1)

s.add();

else

{

cout<<"\nEnter the 2 values";

cin>>p>>q;

s.add(p,q);

}

cout<<"\n1.Add without parameter\n2.Add with parameter\n3.Exit";

cout<<"\nEnter your choice: ";

cin>>ch;

}

}

No comments: