lect6_1

lect6_1 - Function Overloading & Default...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Function Overloading & Default Parameters 1 Overloading Function Names & Functions with Default Parameters Overloading function names In C++, we can use the same function name for two or more functions. Using the the same function name for two (or more) functions is called Function overloading . Overloading is a very useful feature. However, function overloading does require some extra care in the specification of function parameters. Suppose that we write a function, say getSum that takes two numbers and returns the sum of the two as follows. \\ return the sum of the two double getSum(double a, double b) { return (a + b); } Now, suppose that our program also requires another function, that takes three num- bers and returns the sum of the three as follows. \\ return the sum of the three double getSum_three(double a, double b, double c) { return (a + b + c); } In programming languages, such as C, you have no choice but to use different names for different functions. But, C++ allows for a more elegant solution. In C++ we can simply use the same function name for both functions. Function Overloading & Default Parameters 2 For example, we can have the following two functions (with identical names) in the same program. \\ return the sum of the two double getSum(double a, double b ) { return (a + b); } \\ return the sum of the three double getSum(double a, double b, double c) { return (a + b + c); } Now, the function getSum has two function definitions. This is an example of function overloading . In this case we have overloaded the function name getSum . Overloading function names, makes a program easier to read. There is no need to find contrived function names, such as getSum three , just because we already used the most natural name in some other function definition. The question now is - how does the compiler know which function definition to use when a call is made to a function that has two or more definitions? To figure out which function definition to use, the compiler checks the number of arguments and the types of the arguments in the function call. For example the following function call double ave = getSum(10.0, 22.0); invokes the getSum that takes two arguments, and the call double ave = getSum(10.0, 22.0, 33.33); invokes the getSum that takes three arguments....
View Full Document

Page1 / 8

lect6_1 - Function Overloading & Default...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online