Docsity

Function Overloading, Inline Functions & Default Arguments – Complete C++ Notes, Study notes of Information Technology

Partial preview of the text

Download Function Overloading, Inline Functions & Default Arguments – Complete C++ Notes and more Study notes Information Technology in PDF only on Docsity!

Function Overloading,

Inline Functions

Default Arguments

By Anam Javaid COMSATS University Islamabad, Wah Campus

Previous Lecture

Function Call by Value

Function Call by reference

Function Call by Pointers

Default Arguments

  • You can define default values for parameters in a function.
  • C++ allows you to declare functions with default argument values.
The default values are passed to the parameters when a function is
invoked without the arguments.

Default Arguments

  • When a function contains a mixture of parameters with and without
default values, those with default values must be declared last. For
example, the following declarations are illegal:

❑void t1(int x, int y = 0, int z); // Illegal ❑void t2(int x = 0, int y = 0, int z); // Illegal ❑However, the following declarations are fine: ❑void t3(int x, int y = 0, int z = 0); // Legal ❑void t4(int x = 0, int y = 0, int z = 0); // Legal

  • When an argument is left out of a function, all arguments that come after it
must be left out as well. For example, the following calls are illegal:

t3(1, , 20); t4(, , 20); but the following calls are fine: t3(1); // Parameters y and z are assigned a default value t4(1, 2); // Parameter z is assigned a default value

Function Overloading

  • Overloading functions enables you to define the functions with the same name as long as their signatures are different.
  • Overloading functions can make programs clearer and more readable. Functions that perform the same task with different types of parameters should be given the same name.
  • Overloaded functions must have different parameter lists. You cannot overload functions based on different return types.

Ambiguous invocation

  • Sometimes there are two or more possible matches for an invocation of a function, and the compiler cannot determine the most specific match. This is referred to as ambiguous invocation.
  • Ambiguous invocation causes a compile error. Consider the following code:

Ambiguous invocation

Inline Functions

  • C++ provides inline functions for improving performance for short
functions.
  • Implementing a program using functions makes the program easy to
read and easy to maintain, but function calls involve runtime
overhead (i.e., pushing arguments and CPU registers into the stack
and transferring control to and from a function).
  • C++ provides inline functions to avoid function calls. Inline functions
are not called; rather, the compiler copies the function code in line at
the point of each invocation. To specify an inline function, precede
the function declaration with the inline keyword,

Inline Functions

Next Lecture

Recursion