2. Modularity
• Modular programming
– Breaking down the design of a program into individual
components (modules) that can be programmed and tested
independently
– A program divided into several smaller parts which can interact
• How do you solve a big/complex problem?
– Divide it into small tasks and solve each task. Then combine these
solutions.
3. Need for Modular Programming
• When a program becomes very large and complex, it becomes very
difficult task for the programmers to design, test and debug such a
program.
• Therefore a long program can be divided into a smaller program
called modules as the modules can be designed, tested and debugged
separately, the task of programmer becomes easy and convenient.
• It makes your program easy to understand.
• Helps manage complexity
– Smaller blocks of code
– Easier to read
• Encourages re-use of code
– Within a particular program or across
– different programs
• Allows independent development of code/Allow the work to be
divided among the development team
4. Need for Modular Programming(cont..)
• Modules
– Can be written and tested separately
– Testing is easier (smaller)
– Doesn't need to be retested
– Reduces length of program
– Hides details (abstraction)
5. Functions in C++
• Modules in C++ are called functions/Function is the programming technique
used to implement the modules to perform a specific task that we determined
in our solution
• Function - a subprogram that can act on data accepted as an input in the
form of parameter, dose some processing and return a value
• Function has a specific purpose and a name
• Every C++ program has at least one function, main(), where program
execution begins and Terminates and it might contain more than one
function.
• Function out of main is executed/activated only if it is
called/invoked(Functions may interact using function call)
6. Functions in C++ come in two varieties:
• Functions could be:
1. Pre-defined(built-in) library functions: Function
which is pre-defined in the library. E.g: pow(),
sqrt(), cin, sin, tan etc..
2. Programmer-defined functions: the function which
is made by the user (e.g., my_printf,area)
7. Elements of Function
• These functions require three elements:
– Function declaration: used to rate the function
– Function calls: Invoke the function to execute the
function
– Function definition: In this program will defines that
how the function will perform there task.
8. Declaration of Functions
• Functions must be declared before use. In this only the name and the
syntax of the function will written.
• Function must be declared before used
• The declaration tells the compiler
– The name,
– Return type,
– Parameters of the function
• Three ways
– Write your prototype into a file, and then use the #include directive
to include it in your program.
– Write the prototype into the file in which your function is used.
– Define the function before it is called by any other function.
9. Function Prototypes
• The declaration of a function is called its
prototype
• Is a statement - it ends with a semicolon
• It consists of the function's
– return type,
– name,
– parameter list
• Syntax
– return_type function_name (type
[parameterName1], type [ParameterName2] ... );
• E.g. long Area(int, int);
Or
long Area(int length, int width);
10. Function Prototypes
• All functions have a return type – default is int
• If the function doesn’t have a return type void
will be used
– void is a reserved word
• The function prototype usually placed at the
beginning of the program
• The definition of the prototype must be given
• Many of the built-in functions have their
function prototypes already written in the
header files you include in your program by
using #include
11. Defining a Function
• The definition tells the compiler how the function
works.
• Consists of :
– the function header :
• like the function prototype except that the parameters must be
named
• there is no terminating semicolon
– its body
• the task of the function
• Syntax
return_type function_name(parameter
declarations)
{
declarations;
statements;
}
12. Defining a Function
• E.g.
long Area(long l, long w)
{
return l * w;
}
• The return statement without any value is
typically used to exit the function early
• C++ does not allow nested functions
– The definition of one function cannot be
included in the body of another function
• A function definition must agree in return
type and parameter list with its prototype
13. Defining a Function
• If the function returns a value, it’s definition
should end with a return statement
• The body of the function is always enclosed in
braces, even when it consists of only one
statement
• return keyword
– Returns data, and control goes to function’s
caller
• If no data to return, use return;
– Function ends when reaches right brace
• Control goes to caller
14. // Creating and using a programmer-defined function.
#include <iostream.h>
int square( int ); // function prototype
int main()
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call
cout << endl;
return 0; // indicates successful termination
} // end main
// square function definition returns square of an integer
int square( int y ) // y is a copy of argument to function
{
return y * y; // returns square of y as an int
} // end function square
Definition of square. y is a
copy of the argument passed.
Returns y * y, or y squared.
Function prototype: specifies data types
of arguments and return values.
square expects an int, and returns
an int.
Parentheses () cause function to be called.
When done, it returns the result.
1 4 9 16 25 36 49 64 81 100
15. Program Using a Function
#include <iostream.h>
double Celsius_to_Fahr(double); //Function Prototype
int main()
{
double temp,result;
cout<<“enter the temperature”<<endl;
cin>>temp;
result= Celsius_to_Fahr(temp);
cout<<“the corresponding Fahrenheit
is”<<result<<endl;
double Celsius_to_Fahr(double Celsius)
{
double temp; // Declare variables
temp = (9.0/5.0)*Celsius + 32; // Convert
return temp;
}
16. Execution of Functions
• Each function has its own name
• When that name is encountered, called
function call, the execution of the program
branches to the body of that function –
called function
• When the function returns, execution
resumes on the next line of the calling
function
• Functions can also call other functions and
can even call themselves
17.
18. Scope Rules of Functions
• The scope rules of a language are the rules that govern how an object
may be accessed by various parts of your program.
• Refers to where an identifier is accessible in the program
• In other words, the scope rules determine what code has access to a
variable.
• Determines how long it is available to your program and where it can
be accessed
• The scope rules also determine the lifetime of a variable.
• There are three types of variables:
– Local variables,
– Formal parameters, and
– Global variables.
19. Local Variables
• Are variables that are declared inside a function or inside any block of code
and is then local to it(identifiers declared within a function/block )
• Used only by statements located within the block in which it is declared.
• Not known outside its own code block. Thus, statements outside a block
cannot access an object defined within the block.
• Exist only while the block of code in which they are declared is executing.
This means that a local variable is created upon entry into its block,
destroyed upon exit, and its value is lost. the local variables are no longer
available when the function returns.
• variable declared in the inner block overrides the one in the outer block
declared with a same name, within the scope of the inner block.
– E.g.
for(int i = 0;i<5; i++)
cout<<i;
i=+10; // compilation error i is inaccessible
20. Local Variables( Cont.…)
• Declaring Variables Within Iteration and Selection Statements: It
is possible to declare a variable within the initialization portion of a
for loop or the conditional expression of an if, switch, or while. A
variable declared in one of these places has its scope limited to the
block of code controlled by that statement.
• For example, a variable declared within a for statement will be local
to that loop
21. Formal Parameters
• As you know, if a function uses arguments, then it must declare
variables that will accept the values of those arguments.
• These variables are called the formal parameters of the function.
• Aside from receiving the arguments when a function is called, formal
parameters behave like any other local variables inside the function.
• The scope of a parameter is local to its function.
• You must make sure that the formal parameters you declare are of the
same type as the arguments you will pass to the function. formal
parameters can be used as variables in the function
22. Global Variables
• are, in many ways, the opposite of local variables.
• Their scope extends to the entire program. Variables defined
outside of any function have global scope
• known throughout the entire program, can be used by any piece of
code, and maintain their values during the entire execution of the
program.
• Because they are global, they can be accessed by any expression,
regardless of the function in which the expression is located.
• When a global and a local variable share the same name, the local
variable has precedence. Put differently, a local variable will hide a
global variable of the same name.
• Global variables are helpful when the same data is used by several
functions in your program, or when a variable must hold its value
throughout the duration of the program.
23. #include <iostream.h>
void myFunction(); // prototype
int x = 5, y = 7; // global variables
int main()
{
cout << "x from main: " << x << "n";
cout << "y from main: " << y <<
"nn";
myFunction();
cout << "Back from
myFunction!nn";
cout << "x from main: " << x << "n";
cout << "y from main: " << y << "n";
return 0;}
void myFunction()
{
int y = 10;
cout << "x from myFunction:
" << x << "n";
cout << "y from myFunction:
" << y << "nn";
}
Output: x from main: 5
y from main: 7 x from myFunction: 5
y from myFunction: 10
Back from myFunction!
x from main: 5
y from main: 7
25. Parameter Passing Techniques
• In general, there are two ways that a computer language can pass an
argument to a subroutine.
– call-by-value,
– Call-by-reference
• Call-by-value: This method copies the value of an argument into the
formal parameter of the subroutine.
– Value of the function argument passed to the
formal parameter of the function
– Copy of data passed to function
– Changes to copy do not change original
– changes made to the parameters of the subroutine will not affect the arguments
used to call it.
– By default, C++ uses the call-by-value method for passing arguments.
• Copying takes time; therefore, if the parameter is bigger than one of the unit data
types, it's better to use one of the other parameter passing modes.
26. Parameter Passing Techniques(cont..)
• Call-by-reference: This method copies the address of an argument
(not its value) into the parameter.
• Inside the subroutine, this address is used to access the actual
argument specified in the call.
• This means that changes made to the parameter will affect the
argument used to call the subroutine.
• possible for code inside the function to change the value of the
argument outside of the function. Pointers are passed to functions just
like any other values.
• Of course, it is necessary to declare the parameters as pointer types.
• Address of the function argument passed to the
formal parameter of the function
• use this method if the actual parameter needs to change
27. Parameter Passing Techniques(cont..)
• If a formal parameter is a reference parameter
– It receives the address of the corresponding actual parameter
– A reference parameter stores the address of the corresponding
actual parameter
• During program execution to manipulate the data
– The address stored in the reference parameter directs it to the
memory space of the corresponding actual parameter
– A reference parameter receives the address of the actual parameter
• Reference parameters can:
– Pass one or more values from a function
– Change the value of the actual parameter
28. Passing Pointers, Strings and Arrays
• Up to now, the examples in this lesson have only passed simple
variables to functions.
• However, there will be times when you will want to use pointers,
strings and arrays as arguments.
• Calling Functions with pointers
– C++ allows you to pass a pointer to a function. To do so, simply declare
the parameter as a pointer type. E.g:
29. //E.g1: Passing pointers to
functions(Sum of 2 num)
#include<iostream.h>
int add(int *i, int *j);//Declaration
int main(){
int i=5; int y=8;
int *p1=&i;
int *p2=&y;
int s=add(p1,p2);//Caller
cout<<s;
return 0;
}
//Function Definition
int add(int *i, int *j){
return *i+*j;
}
// E.g1 Passing pointers to
Functions(Max of 2 num)
#include<iostream.h>
int Max(int *i, int *j);
int main(){
int i=5; int y=8;
int *p1=&i; int *p2=&i;
cout <<Max(p1,p2);//Call
return 0; }
int Max(int *i, int *j){ //Definition
int m;
if(*i>*j)
m=*i;
else
m=*j;
return m;}
30. Passing Pointers, Strings and Arrays (cont.…)
• Calling Functions with Arrays: When an array is an argument to a
function, only the address of the first element of the array is passed,
not a copy of the entire array.
• There are three ways to declare a parameter that is to receive an
array pointer:
– Formal parameter as sized array, it can be declared as an array
of the same type and size as that used to call the function, as shown
here: void display(int num[10]);
– Formal parameter as an unsized array way to declare an array
parameter is to specify it as an unsized array, as shown here:
void display(int num[]) ;
– Formal parameter as a pointer, it can be declared as a pointer.
This is the method most commonly used in professionally written
C++ programs. Here is an example: void display(int *num) ;
31. //E.g1 Passing arrays to
//functions as sized Array
#include<iostream.h>
//Declaration
double Avg(int Arr[], int size);
int main(){
int arr[]={10,20,21,30,30};
int avg=Avg(arr,5); //Calling
cout<<"average=:"<<avg;
return 0; }
//Definition
double Avg(int Arr[], int size){
int sum=0; double avg;
for(int i=0;i<size; i++){
sum+=Arr[i];
}
avg=double(sum)/size;
return avg; }
//E.g2 Passing arrays to
//functions as unsized Array
#include<iostream.h>
//Declaration
double Avg(int Arr[]);
int main(){
int arr[]={10,20,21,30,30};
int avg=Avg(arr); //Calling
cout<<"average=:"<<avg;
return 0; }
//Definition
double Avg(int Arr[]){
int sum=0; double avg;
for(int i=0;i<5; i++){
sum+=Arr[i];
}
avg=double(sum)/5;
return avg; }
32. //E.g3 Passing arrays to funtions as pointers
#include<iostream.h>
double Avg(int *Arr); //Declaration
int main(){
int arr[]={10,20,21,30,30};
int avg=Avg(arr); //Calling
cout<<"average=:"<<avg;
return 0; }
//Function Definition
double Avg(int *Arr){
int sum=0; double avg;
for(int i=0;i<5; i++){
sum+=Arr[i];
}
avg=double(sum)/5;
return avg;
}
33. Passing Pointers, Strings and Arrays (cont.…)
• Calling Functions with Strings: As you know, strings are simply
character arrays that are null-terminated.
– Thus, when you pass a string to a function, only a pointer to the
beginning of the string is actually passed.
– This is a pointer of type char *.
– E.g. void stringupper(char *str);
// Calling Functions with Strings.
#include <iostream>
using namespace std;
int mystrlen(char *str);//Declaration
int main(){
cout << "Length of Hello There is: ";
cout << mystrlen("Hello There");//Call
return 0;
}
//Function Definition.
int mystrlen(char *str)
{
int i;
for(i=0; str[i]; i++) ;
return i;
}
34. Functions in C++ come in two varieties:
• Functions could be:
1. Pre-defined(built-in) library functions: Function which is
pre-defined in the library. E.g: pow(), sqrt(), cin, sin, tan
etc..
2. Programmer-defined functions: the function which is made
by the user (e.g., display, add,area..)
35. Type of User-defined Functions in C++
• There can be 4 different types of user-defined functions, they are:
– Function with no arguments and no return value
– Function with no arguments and a return value
– Function with arguments and no return value
– Function with arguments and a return value
• Which method is better? All four function programs can gives the
same output and can be used to write technically correct program.
Thus there is no hard and fast rule on which method should be
chosen. The particular method is chosen depending upon the
situation and how you want to solve a problem.
36. • Function with no arguments and no return value: Such functions
can either be used to. display information or they are completely
dependent on user inputs
• Below is an example of a function, which takes 2 numbers as input
from user, and display which is the greater number.
#include<iostream.h>
// function declaration
void greatNum();
int main()
{
// function call
greatNum();
return 0;
}
// function definition
void greatNum()
{ int i, j;
cout<<"Enter the no you want to compare.";
cin>>i>>j;
if(i > j) {
cout<<"The greater number is:”<<i;
}
else {
cout<<"The greater number is:”<<j;
}
}
37. • Function with no arguments and a return value:
• Below is an example of a function, which takes 2 numbers as input
from user, and display which is the greater number.
#include<iostream.h>
// function declaration
int greatNum();
int main()
{
int res;
// function call
res = greatNum();
cout<<" greater- no is”<< res;
return 0;
}
int greatNum() // function definition
{ int i, j, greatnum;
cout<<"Enter the no to compare.";
cin>>i>>j;
if(i > j) {
greatnum=i;
}
else {
greatnum=j;
}
return greatnum;
}
38. • Function with arguments and no return value:
• Below is an example of a function, which takes 2 numbers as input
from user, and display which is the greater number.
#include<iostream.h>
// function declaration
void greatNum(int a, int b);
int main()
{
int a, b;
cout<<"Enter the no to compare.";
cin>>a>>b;
// function call
greatNum(a,b);
return 0;
}
// function definition
void greatNum(int a, int b){
if(a > b) {
cout<<" greater- number is:”<<a;
}
else {
cout<<" greater- number is:”<<b;
}
}
39. • Function with arguments and a return value: This is the best type,
as this makes the function completely independent of inputs and
outputs, and only the logic is defined inside the function body.
• Below is an example of a function, which takes 2 numbers as input
from user, and display which is the greater number.
#include<iostream.h>
// function declaration
int greatNum(int a, int b);
int main()
{
int a, b, res;
cout<<"Enter the no to compare.";
cin>>a>>b;
// function call
res=greatNum(a,b);
cout<<" greater- no is”<< res;
return 0;
}
// function definition
int greatNum(int a, int b){
int greatnum;
if(a > b) {
greatnum=a;
}
else {
greatnum=b;
}
return greatnum;
}
40. Arguments to main( ) [argc and argv]
• Sometimes you will want to pass information into a program when
you run it. This generally is accomplished by passing command line
arguments to main( )
• A command line argument is information specified on the command
line after a program’s name(e.g: $ ./a.out hello people)
• To pass command line arguments, we typically define main() with two
arguments which are argc and argv as follows:
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
• C++ defines two built-in conventionally named, but optional,
parameters to main( ), to receive the command line arguments.
41. Arguments to main( ) [argc and argv](cont..)
• argc: stands for argument count usually has type int
– is an integer parameter that holds the number of arguments on the
command line.
– tells you how many command-line arguments there were. It will
always be at least 1, because the name of the program is also counted.
• argv: stands for argument values
– is a pointer to an array of character pointers and usually has the
type char**[] or char* [] .
– Each pointer in the argv array points to a string containing a
command line argument.
– The program’s name is pointed to by argv[0]; argv[1] will point to
the first argument, argv[2] to the second argument, and so on.
– All command line arguments are passed to the program as strings,
so numeric arguments will have to be converted by your program
into their proper internal format.
42. • The following program demonstrates how to access the command line
arguments.
// Name of program file1.cpp
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cout << "You have entered " << argc
<< " arguments:" << "n";
for (int i = 0; i < argc; ++i)
cout << argv[i] << "n";
return 0;
}
Input:
$ g++ file1.cpp –o out
$ ./out geeks for geeks
Output:
You have entered 4 arguments:
./out
geeks
for
Geeks
43. The return Statement
• The return statement performs two important operations:
– Cause a function to return immediately to its caller.
– Return a value.
• Returning from a Function: function returns to its caller in one of two
situations: either when the function’s closing curly brace is encountered or
when a return statement is executed.
• The return statement can be used with or without an associated value.
– Functions that are declared as returning a value (i.e., that have a non-
void return type) must return a value.
– Only functions declared as void can use return without a value.
• For void functions, the return statement is mostly used as a program-control
device. It can act as a control statement designed to prevent part of the
function from executing.
• Even though it can unclear the operation of a algorithm and confuse its
meaning its possible to use multiple return statements
44. The return Statement(cont…)
• Returning Values: Every function, unless it is of type void, returns a
value. This value is specified by the return statement.
– Do not forget to assign the returned value to variables, to use by the cout
statement or any expression. Unless otherwise the return value is lost or
discarded.
– Functions that don’t return values are declared void.
• Functions That Return Pointers: Functions can return pointers.
Pointers are returned like any other data type, and they pose no special
problem
– In order to return a pointer, a function must declare its return type to be a
pointer. E.g, The return type of f( ) is declared to be an integer pointer:
int *f();
– If a function’s return type is a pointer, then the value used in its return
statement must also be a pointer. (As with all functions, the return value
must be compatible with the return type.)
45. • The following program demonstrates the use of a pointer return
type.
//Functions returning pointers in C++
#include<iostream.h>
int * biger(int &y, int &n); //Declaration
int main(){
int num1, num2, *c;
cout<<"Enter two integersn";
cin>>num1>>num2;
c = biger(num1, num2); //Calling
cout<<"The bigger value = "<<*c;
}
//Definition
int * biger(int &x, int &y){
if(x>y) {
return(&x);
}
else
{
return(&y);
}
}
46. • The following program demonstrates the use of a pointer return
type.
/* This C++ program demonstrates
about functions returning pointers in
C++ */
#include<iostream.h>
int * biger(int &y, int &n);
int main(){
int num1, num2, *c;
cout<<"Enter two integersn";
cin>>num1>>num2;
c = biger(num1, num2);
cout<<"The bigger value = "<<*c;
}
int * biger(int &x, int &y)
{
int *p1, *p2;
if(x>y)
{
p1=&x;
return p1; }
else
{
p2=&y;
return p2;
}
}
47. Functions with Default Parameters
• In C++ programming, you can provide default values
for function parameters.
• The idea behind default argument is simple. If a function is called by
passing argument/s, those arguments are used by the function.
• But if the argument/s are not passed while invoking a function then,
the default values are used.
e.g. void add(int a, int b, int c, int d = 4);
• All of the default parameters must be the rightmost parameters of the
function
• In a function call where the function has more than one default
parameter and a value to a default parameter is not specified
– You must omit all of the arguments to its right
• Default values can be constants, global variables, or function calls
49. Common mistakes when using Default argument
• void add(int a, int b = 3, int c, int d = 4);
– The above function will not compile. You cannot miss a default
argument in between two arguments.
– In this case, c should also be assigned a default value.
• void add(int a, int b = 3, int c, int d);
– The above function will not compile as well. You must provide
default values for each argument after b.
– In this case, c and d should also be assigned default values.
– If you want a single default argument, make sure the argument is
the last one. void add(int a, int b, int c, int d = 4);
• You cannot assign a constant value as a default value to a reference
parameter
50. Example: Default Argument
// C++ Program to demonstrate working of default argument
#include <iostream>
using namespace std;
void display(char = '*', int = 1);
int main(){
cout << "No argument passed:n";
display();
cout << "nFirst argument passed:n";
display('#');
cout << "nBoth argument passed:n";
display('$', 5);
return 0;
}
void display(char c, int n){
for(int i = 1; i <= n; ++i) {
cout << c;
}
cout << endl;
}
Output
No argument passed:
*
First argument passed:
#
Both argument passed:
$$$$$
51. Recursion and Recursive Functions
• Recursion is the process of defining something in terms of itself.
• As it relates to programming, a function that calls itself is said to be
recursive
– Main calls another function…..normal
– A function calls another function2….normal
– A function calls itself ?! Possible?? YES
A recursive function is one that call itself.
• The main advantage of recursive functions is that they can be used to
create clearer and simpler versions of several algorithms than those
produced with their iterative relatives
52. Concept Of recursion
• A function can also call itself, this is known as recursion
• To avoid infinite recursion, one must have a terminating condition in the
function
• A recursive function is called to solve a problem
• The function knows to solve only the simplest cases or so-called base-
cases
• Thus if the function called with a base-case, it simply returns a result.
But if it is called with more complex problem, the function divides the
problem into two conceptual pieces.
• How a particular problem is solved using recursion?
– The idea is represent a problem in terms of one or more smaller
problems, and add one or more base conditions that stop recursion.
– E.g: we compute factorial n if we know factorial of (n-1). Base
case for factorial n would be n=0. we return 1 when n=0.
53. Concept Of recursion (cont.)
• Thus the function launches (calls) a fresh copy of itself to work
on the smaller problem –this is related as a Recursive-
call/recursive step.
• The function keeps dividing each new sub problem into two
conceptual pieces until eventually terminates after converging on
the base-case.
• The function thus recognize the base-case and returns a result to
the previous copy of the way up the line until original call of the
function returns the final result to main.
55. //Recursive factorial Function
#include<iostream.h>
#include<iomonip.h>
unsigned lion factorial(unsigned long);//prototype
int main()
{
int num;
cout<<“enter a positive integer:”;
cin>>num;
cout<<“factorial=“<<factorial(num);
return 0;
}
unsigned long factorial(unsigned long n)
{
if ( n <= 1) //the base case
return 1;
else
return n * factorial (n - 1);
}
Finding Factorial Recursively
56. • Function overloading
– Functions with same name and different parameters
– Should perform similar tasks
• I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
• A call-time c++ complier selects the proper function by examining the
number, type and order of the parameters.
• No matter how you use default arguments, a function should always
be written so that it serves only one purpose.
• If your function does more than one thing or the logic seems too
complicated, you can use Function overloading to separate the logic
better.
Function Overloading
57. Function Overloading(cont..)
• In C++, two or more functions can share the same name, as long as their
parameter declarations are different. In this situation, the functions that share
the same name are said to be overloaded, and the process is referred to as
function overloading.
• Function overloading is the mechanism that allows two related functions to
share the same name.
• Because of the difference, the compiler is able to call the correct version of
each function.
• The compiler uses the type and/or number of arguments as its guide to
determining which version of an overloaded function to call. Thus,
overloaded functions must differ in the type and/or number of their
parameters.
• While overloaded functions may have different return types, the return
type alone is not sufficient to distinguish two versions of a function.
(Return types do not provide sufficient information in all cases for the
compiler to correctly decide which function to use.)
58. • In C++ programming, two functions can have same name if number
and/or type of arguments passed are different.
• These functions having different number or type (or both) of
parameters are known as overloaded functions. For example:
– int test() { }
– int test(int a) { }
– float test(double a) { }
– int test(int a, double b) { }
• Here, all 4 functions are overloaded functions because argument(s)
passed to these functions are different.
• Overloaded functions may or may not have different return type but it
should have different argument(s).
• Using different names to related function makes the situation more
59. Function Overloading and Ambiguity
• Ambiguity results when the compiler cannot resolve the difference between
two overloaded functions.
• It is possible to create a situation in which the compiler is unable to choose
between two (or more) correctly overloaded functions. When this happens,
the situation is said to be ambiguous.
• Ambiguous statements are errors, and programs containing ambiguity will
not compile.
• By far the main cause of ambiguity involves C++’s automatic type
conversions. C++ automatically attempts to convert the type of the
arguments used to call a function into the type of the parameters defined by
the function.
60. • When myfunc( ) is called using the integer 10, ambiguity is introduced,
because the compiler has no way of knowing whether it should be converted
to a float or to a double(Both are valid conversions)
• This confusion causes an error to prevents the program from compiling.
• The central issue is that it is not the overloading of myfunc( ) relative to
double and float that causes the ambiguity. Rather, the confusion is caused
by the specific call to myfunc( ) using an indeterminate type of argument.
float myontfunc(float i)
{
return i;
}
double myfunc(double i)
{
return -i;
}
// Overloading ambiguity example.
#include <iostream>
using namespace std;
float myfunc(float i);
double myfunc(double i);
int main() {
// unambiguous, calls myfunc(double)
cout << myfunc(10.1) << " ";
// ambiguous
cout << myfunc(10);
return 0;
}