4 Function Overloading and References



Function overloading:
Polymorphism means one thing having many forms and hence function polymorphism means one function having many forms.  Thus function overloading facilitates defining several functions with the same name, thus overloading the function name in function overloading compiler uses the context to determine which definition of an overloaded function is to be invoked.

Function overloading is used to define a set of functions that essentially, do the same thing using different argument lists.  Argument list of a function is called as function’s signature. 

Example 1.
#include<stdio.h>
long iraseto(int num, int power){
long lp =l;
do
{
lp *= num;
}while (--power);
return(lp);
}
double draiseto(double num, int power){
double dp =l;
do
{
dp *= num;
}while(--power);
return(dp);
}
void main (void){
printf(“ 2 raiseto 8 %1d\n”, raiseto(2,8));
printf(“ 2.5  raiseto 8 %lf\n”, deraiseto(2.5, 2));
}
in the above program the two functions does the same job, raise a given number to a given power.  On different data types i.e. integer and double.  Return types of both functions are different. 

Function overloading facilitates use of such functions by giving them the same name:-

Example 2
#include<stdio.h>
double riseto(double num, int power)
{
double dp =l;
do
{
dp *= num;
}while(--power);
return(dp);
}
long raiseto(int num, int power)
{
long lp = l;
do
{
lp *= num;
}while(--power);
return(lp);
}
void main (void){
printf(“ 2 raiseto 8 %1d\n”, raiseto(2,8));
printf(“ 2.5 raiseto 2 %1f\n”, raiseto(2.5, 2));
}
A program can overload a function for each of the data type it wants.  For example

Example 3
#include<stdio.h>
void print(Char *s)
{
printf(“%s\n”,s);
}
void print(int i)
{
printf(“%d\n”,i);
}
void print(long l)
{
printf(“%ld\n”,l);
}
void print(double d)
{
printf(“%lf\n”,d);
}
void print(float f)
{
printf(“%f\n”,f);
}
void main(void)
 {
float ff             = 1021.12;
double dd        = 13414.123441L;
long ll              = 2234521L;
int ii                 = 123;
char *string     = “Hello High….”;
print(ii);           // integer
print(ll);           // long
print(string);    // character string
print(ff);          // float
print(dd);         // double
}

With function overloading, different functions to print different data types do not require different names.  Function overloading is allowed only of the functions have a different signature.  In other words, one function’s argument list should not be same as that of the other.

The facility of function overloading should not be overused.  Only those functions which basically do the same task, on different sets of data, should be overloaded.  As in function overloading, more than one function has to be actually defined and each of these occupy memory.

Call by Reference:  
In C++ a function can be called by call by reference where changes made to the formal variable as they are called, are not reflected back in calling function.  Passing an address allows changes to be made directly to the memory are occupied by actual variable.  A call by address requires formal variables to be considered as pointers and so indirection operator has to be used with them.  A reference on the other hand, is another name for a previously defined variable.  Thus after a reference is defined for a particular variable, the variables can be referred to by using its original name and reference.  Hence reference is an alias.  When a reference or alias of a variable is passed to a function it is called as a call by reference.

Usage of reference Variables:
C and C++ users ampersand(&) symbol as address operator.  It is also overloaded to perform binary AND operation on its operands.  This operator can be overloaded to declare a reference variable just like a pointer variable is declared using indirection operator(*)

Example 4
int num = 10;               // int variable
int *ip  = &num;         // pointer to integer
int &ir =  num; // reference variable
#include<stdio.h>
void main(void)
{
int num =10;
int &ir = num;
printf(“num = %d\n”,num);

printf(“& num = %u\n”,num);
printf(“ir = %d\n”,ir);
printf(“& ir= %u\n”,&ir);
ir = 123;
printf(“after change\n”);
printf(“num = %d\n”,num)
printf(“ir = %d\n”,ir);
}

A reference variable declared in a function should be initialized at the time of its declaration itself.  Also, once a reference has been made to variable, it cannot be changed to refer to another variable.

Example 5
#include<stdio.h>
void main(void)
{
int num1 =10;
num2 = 200;
int &ref = num1;
printf(“\nnum1 = %d\n”,num1);
printf(“num2 = %d\n”,num2);
printf(“ref = %d\n”,ref);
ref = num2;
printf(“after change\n”);
printf(“num1 = %d\n”,num1);
printf(“num2 = %d\n”,num2);
printf(“ref = %d\n”,ref);
}

Passing  references to functions:
Reference variables are useful for passing functions.  A call by reference creates an alias in called function for the variable from the calling function.  Changes made to variable using the alias in called function are reflected back in the calling function.  This facility can be used to make changes to more than one variable from within the function. 

Example 6
#include<stdio.h>
void val_swap(int x, int y){
t  = x;
s =  y;
y = t;
}
void add_swap(int *x, int *y){
int t;
t = *x;
*x = *y;
*y = t;
}

void ref_swap(int &x, int &y){
int t;
t = x;
x = y;
y = t;
}
void main (void){
int n1 = 25;
int n2 = 50;
printf(“Before any swap:”);
printf(“n1 = %d and n2= %s\n”, n1, n2);
val_swap(n1,n2);
printf(“After Call by Value”);
printf(“n1 = %d and n2= %s\n”, n1, n2);
add_swap(&n1, &n2);
printf(“After Call by Address”);
printf(“n1 = %d and n2= %s\n”, n1, n2);
ref_swap(n1, n2);
printf(“After Call by Reference”);
printf(“n1 = %d and n2= %s\n”, n1, n2);
}
NOTE: Reference variables reduce the need of pointers to reflect changes to more than one variable from within a function.

A reference variable can refer to any integer variable, be it at array, or be it a member variable from a structure or class.  reference variable can refer to constants as well. 

Example 7
#include<stdio.h>
void somefn(int &intref){
++intref;
}
void main(void){
int sint = 10;
long lint = 20;
printf(“Before incrementing….\n”);
printf(“Small Int = %d\n”,sint);
printf(“Long int = %d\n”,lint);
somefn(sint);                           //  int variable
somefn(lint);                            // long variable
printf(“After incrementing….\n”);
printf(“Small int = %d\n”,sint);
printf(“Long int = %d\n”,lint);
somefn(25);                             // int variable
somefn(sint +10);                    // expression
}
Since mismatch between data types of the actual argument and formal argument is shielded by these temporary reference variable, programs prefer to use pointers if a function has to change the values of an argument.

Practical Session 4
Example 1
#include<iostream.h>
#include<string.h>
#include<conio.h>
const int MAX_ITEMS=25;
class bag{
private:
            int contents[MAX_ITEMS];
            int itemcount;
public:
            bag( )
            {
            itemcount=0;
            }
            bag(int item)
            {
            contents[0]=item;
            itemcount=1;
            }
            void put(int item)
            {
            contents[itemcount++]=item;
            }
            void show( );
            };
void bag::show( )
{
for(int i=0;i<itemcount;i++)
{
if (itemcount)
{
cout<<contents[i];
cout<<"\t";
}
else
{
cout<<"\n NIL ";
cout<<endl;
}
}
}
void main( ){
clrscr( );
int item;
bag b1;
bag b2=4;
cout<<"\n Gifted Bag1 initially has  : ";

b1.show( );
cout<<"\n Gifted Bag2 initially has  : ";
b2.show( );
while(1){
cout<<"\n Enter item number to put in bag  : ";
cin>>item;
if(item==0)
{
break;
}
b2.put(item);
cout<<"\n Item in the bag2 : ";
b2.show( );
}
getch( );
}

Example 2
#include<iostream.h>
#include<conio.h>
class distance{
private:
            float feet;
            float inches;
public:
            void init(float ft,float in){
                        feet =ft;
                        inches=in;
            }
            void read( ){
            cout<<"\n Enter Feet    : ";
            cin>>feet;
            cout<<"\n Enter Inches  : ";
            cin>>inches;
            }
            void show( )    {
            cout<<"\n\n Feet "<<inches<<"\'";
            }
            void add(distance d,distance d1){
            feet   = d.feet   + d1.feet;
            inches = d.inches + d1.inches;
            if(inches>12.00){
            feet  = feet+1.0;
            inches= inches-12.00;
            }
    }
};
void main( ){
clrscr( );
distance d,d1,d2;

d1.init(11.00,6.25);
d.read( );
cout<<"\n Distance d is : ";
d.show( );
cout<<"\n Distance d1 is : ";
d1.show( );
d2.add(d,d1);
cout<<"\tn Distance d + d1 is : ";
d2.show( );
getch( );
}

Example 3
#include<iostream.h>
#include<string.h>
#include<conio.h>
void show(int val){
cout<<"\n Integer    : "<<val;
}
void show(double val){
cout<<"\n Double     : "<<val;
}
void show(char *val){
cout<<"\n Character  : "<<val;
}
void main( ){
clrscr( );
show(240);
show(45.50);
show("Hello Sandhya");
getch( );
}

Example 4
#include<iostream.h>
#include<conio.h>
void percent(int per,char style);
void main( ){
clrscr( );
int m1,m2,m3,m4;
cout<<"\n Enter Percent of Mahesh   : ";
cin>>m1;
cout<<"\n Enter Percent of Sandhya  : ";
cin>>m2;
cout<<"\n Enter Percent of Madhuri  : ";
cin>>m3;
cout<<"\n Enter Percent of Anand    : ";
cin>>m4;
cout<<"\n Mahesh   : ";
percent(m1,'*');
cout<<"\n Sandhya  : ";
percent(m2,'\xCD');
cout<<"\n Madhuri  : ";
percent(m3,'&');
cout<<"\n Anand    : ";
percent(m4,'!');
getch( );
}
void percent(int per,char style)
{
for(int j=0;j<per/2;j++)
{
cout<<style;
}
}

Example 5
#include<iostream.h>
#include<conio.h>
void swap(char &x,char &y)
{
char t;
t=x;
x=y;
y=t;
}
void swap(int &x,int &y)
{
int t;
t=x;
x=y;
y=t;
}
void swap(float &x,float &y)
{
float t;
t=x;
x=y;
y=t;
}
void main( )
{
clrscr( );
char c1,c2;
int a,b;
float c,d;
cout<<"\n Enter two Characters     :\n ";
cin>>c1>>c2;
swap(c1,c2);
cout<<"\n On swapping of C1 and C2 : "<<c1<<"\t"<<c2;
cout<<"\n\n\n Enter Two numbers    :\n ";
cin>>a>>b;
swap(a,b);
cout<<"\n On swapping of A and B   : "<<a<<"\t"<<b;
cout<<"\n\n\n Enter Two Floats     :\n ";
cin>>c>>d;
swap(c,d);
cout<<"\n On swapping of C and D   : "<<c<<"\t"<<d;
getch( );
}

Example 6
#include<iostream.h>
#include<string.h>
#include<conio.h>
void print( ){
static int count=1;
cout<<"\n count : "<<count;
count++;
}
void printcount( ){
int count=1;
cout<<"\n\t\t print count : "<<count;
count++;
}
void main( ){
clrscr( );
print( );
print( );
print( );
printcount( );
printcount( );
printcount( );
getch( );
}

Example 7
#include<iostream.h>
#include<conio.h>
class date{
int day;
int month;
int year;
public:
date( )
{
day=0;
month=0;
year=0;
}
date(int d,int m,int y) {
day=d;
month=m;
year=y;
}
void read( ){
cout<<"\n Enter date<dd/mm/yyyy> : ";
cin>>day>>month>>year;
}
void show( ){
cout<<"\n day "<<" : "<<day<<"/"<<month<<"/"<<year;
}
int isleapyear( ){
if(year %4 == 0){
return 1;
}
else{
return 0;
}
}
int thismonthday( ){
int m[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
if(month ==2 && isleapyear( ))
{
return 29;
}
else
{
return m[month-1];
}
}
void operator ++( ){
++day;
if(day>thismonthday( )){
day=1;
month++;
}
if(month>12)
{
month=1;
year++;
}
}
};
void nextday(date &d){
cout<<"\n Date ";
d.show( );
++d;
cout<<"\n on increment becomes ";
d.show( );
cout<<endl;
}
void main( ) {
clrscr( );
date d1(14,4,1976);
date d2(28,2,1992);
date d3(28,2,1993);
date d4(31,12,1995);
nextday(d1);
nextday(d2);
nextday(d3);
nextday(d4);
date today;
today.read( );
nextday(today);
getch( );
}
Example 8
#include<iostream.h>
#include<conio.h>
class index5{
private:
int value;
public:
index( ){
value=0;
}
index(int val){
value=val;
}
int getindex( ){
return value;
}
boolean operator <(index idx){
return (value<idx.value? true:false);
}
};
void main( ){
clrscr( );
index idx1 = 5,idx2=10;
cout<<"\n Index 1 "<<idx1.getindex( );
cout<<"\n Index 2 "<<idx2.getindex( );
if(idx1<idx2){
cout<<"\n Index 1  is less thane idx 2";
}
else{
cout<<"\n Index 2 is less than idx 1 ";
}
getch( );
}

Top

No comments:

Post a Comment