You are on page 1of 2

LAB 8 – C++ LANGUAGE AND FUNCTIONS-II

Objectives
1. Writing overloaded functions.
2. Passing arguments by reference.

Function Overloading
With function overloading, multiple functions can have the same name with different
parameters:
Example:
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
Notice that all the functions have same name, but the only distinguishing factor is the
number of arguments being passed while calling the function. The different functions
with same names are also called prototypes of that function i.e. in above example
myFuntion have 3 prototypes.

Task 8.1 : Example Code:


int plusFunc(int x, int y) {
return x + y;
}

double plusFunc(double x, double y) {


return x + y;
}

int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}

Output:

Exercise 8.1:
Write a C++ program using function overloading. The name of the overloaded
function is ‘square’. The different prototypes of this overloaded function are;
 void square(void);// Used to print a solid square of *s with side length of 5
 void square (char);// Used to print a solid square of the character passed as
argument with side length of 6
 void square(char, int);// Used to print a solid square of the character and
the side length passed as arguments to this function
Make calls to these functions one by one in your program.

Exercise: 8.2: (Use Global Variables)


Write a function ‘swap’ in C++ language that swaps the values of two variables
passed as arguments to this function. Write a C++ program which takes values of two
integer variables from the user and swaps their values using function ‘swap’. Your
program should have the following interface.
Enter the first value : 6
Enter the second value : 9
The two numbers have been swapped.
The first number is now 9.
The second number is now 6.

Web Resources

http://www.cplusplus.com/doc/tutorial/

You might also like