8 Functions in Action

 

This chapter covers

  • Understanding what functions are, and how to define and declare functions.
  • Get a first insight to function overloading.
  • Learn how to manage and use recursive functions
  • Understand function templates and their role.
  • Learn the difference between Macros and functions.

In this chapter, you will learn all about functions. Although you have already used several functions in your code practice, up until now, you have primarily utilized pre-written functions, which are part of the C++ Standard Library. For example, when you wanted to insert elements into a string or a vector, you used the insert() function, or when you wanted to erase elements from a vector, you used the erase() function. These functions are part of the library's collection of utility functions. Using these standard library functions[1] you have learned so far, was straightforward and efficient.

In this chapter, you will move one step up the ladder, and learn how to write your own functions. You will learn how to define functions, declare them, (create a function prototype), and how to implement functions and combine them with other elements in your code.

You will also learn about the difference between passing values to a function by reference, which means passing the memory address of the variable, and by value, which means passing a copy of the variable.

8.1 Functions are the new black (box)

8.1.1 Function definition – how to define your function

8.1.2 Form follows function: Understanding functions

8.1.3 Function declaration

8.2 Under the hood of function calls

8.3 The load is on - Function overloading

8.4 Function recursion Function recursion Function recursion

8.5 Function Templates – write once, then reuse, reuse reuse.

8.6 Passing an array to a function

8.7 Macros, Inlines, and functions – what the fuss is about?

8.8 Summary