You are on page 1of 7

Functions with

references
Prepared By Dalton Ndirangu
Reference Parameters
Cont..
Example: Swapping two numbers
#include<iostream>
using namespace std;

//declaration
void swap(int &, int &);

//function definition
void swap(int &a, int &b)
{
int temp=a;
a=b;
b=temp;
}

int main()
{
int x,y;
cout<<"Enter two numbers";
cin>>x>>y;

cout<<"Numbers before swaping (interchanging) are "<< x << " and " << y;

swap(x,y);

cout<<" Numbers after swaping (interchanging) are " << x <<" and "<<y;

system("pause");

return 0;
}
Polymorphism and Overloading

 C++ allows polymorphism, i.e. it allows more than one function to have the
same name, provided all functions are either distinguishable by the typing or
the number of their parameters. Using a function name more than once is
sometimes referred to as overloading the function name. Here's an example:
Example: adding two numbers using
polymorphic function
#include<iostream>
using namespace std;

//function declarations
int adding (int , int);
float adding(float, float);
float adding(int, float, float);
double adding(double,double, double);

//functions definitions
int adding(int a, int b)
{
int sum=a+b;

return sum;
}

float adding(float a, float b)


{
float sum;
sum=a+b;

return sum;
}

float adding(int a, float b, float c)


{
float sum=a+b+c;

return sum;
}

double adding(double a, double b, double c)


{
double sum=a+b+c;

return sum;
}
Cont..
int main()
{
cout<<adding(10,20)<<endl;
cout<<adding(5.7, 4.5, 667.66)<<endl;
cout<<adding(45, 67.999)<<endl;
cout<<adding(345.66, 5656.777, 454.5656)<<endl;

system("pause");
return 0;
}

You might also like