1. Lecture 05
Overloaded Functions
and
Inline Functions
Learn about:
Some functions that are not supported in C:
- Overloaded
- inline functions
- default arguments.
Ref.: OOP using C++, Joyce Farrel, Thopson Learning
1
2. Overloaded Functions (page 146-148)
• Overloaded functions are functions that have
similar name but each performs different
activities depending on the kind of data sent to
the function.
• The compiler uses the number of arguments,
and their data types, to distinguish one
function from another.
• Function overloading is not allowed in C.
2/15
5. Inline Functions (page 143-144)
• Functions are good for structured programming
but incur runtime overhead.
• An inline function is written like a normal
function but compiles into inline code which is
inserted into the program wherever a function
call occurs.
• Inline functions are not allowed in C.
5/15
6. Inline Functions : Overhead
: memory
: a 10
int main() {
func1(10, 20); b 20
: x 30
:
func1(40,50); • passing control to the function.
:
: • placing argument values in a memory.
} • returning to proper point in the
calling program.
void func1(int a, int b) {
: • providing a memory for any returned
x = a + b; value
:
} 6/15
7. Inline Functions: Example 1
#include <iostream.h>
inline void lbstokg(float pounds)
{
0.453592 * pounds;
}
void main()
{ float lbs;
cout<<"Enter weight in pounds: ";
cin>>lbs;
cout<<"Your weight in kg is "
<< lbstokg(lbs) << endl;
}
0.453592 * lbs
7/15
9. Inline Functions Vs Macros
• Inline functions are similar to macros declared
with the #define directive. The major
differences are:
– Inline functions are recognized by the compiler.
Macros are implemented by a simple text
substitution.
– Compiler performs type checking on the parameters
of an inline function. Macros have unwanted side
effects.
9/15
10. Inline Functions Vs Macros
Example
#include <iostream.h>
#define MAX(A,B) ( (A) > (B) ? (A) : (B))
inline int max(int a, int b) void main()
{ if (a > b) { int result,x,y;
return a; x = 23; y = 45;
result = MAX(x++, y++);
else cout << x << y << "n";
return b;
} x = 23; y = 45;
result = max(x++, y++);
cout << x << y << "n";
}
Output from the program:
2447
10/15
2446
12. Default Arguments (page 144 - 146)
• A function can be called without specifying all
its arguments.
• The function declaration must provide default
values for those arguments that are not
specified.
• Default arguments are not allowed in C.
12/15