Sunday 13 September 2009

Advanced features of C++ functions

There are 3 advanced features of C++ functions as compared to C. They are Call by Reference, Function Overloading and Default Arguments. You can read more about them here.

A simple program showing all the three features as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example of pointer to const and const pointer
#include<iostream>

using namespace
std;

//Call by reference
void swap(int& a, int &b)
{

int
temp = a;
a = b;
b = temp;
}


//Overloaded function: Call by reference (pointers)
void swap(int *a, int *b)
{

int
temp = *a;
*
a = *b;
*
b = temp;
}


//Pass by value with Default arguments
void doSwap(int a, int b = 1)
{

swap(a,b);
cout<<"After Local Swap: a = "<< a <<" b = "<< b <<endl;
}


int
main()
{

int
a = 10, b = 17;
cout<<"Before Swap : a = "<< a <<" b = "<< b <<endl;
swap(a, b);
cout<<"After Swap 1: a = "<< a <<" b = "<< b <<endl;
swap(&a, &b);
cout<<"After Swap 2: a = "<< a <<" b = "<< b <<endl;
doSwap(a, b);
doSwap(a);
cout<<"After DoSwap: a = "<< a <<" b = "<< b <<endl;

return
0;
}






The output is as follows:


No comments:

Post a Comment