- [Instructor] Functions are fundamental to C++.
Even in its object model, functions are the basis
of class methods.
All code in a C++ program happens in functions,
starting with the main function.
A function is a block of code that may be called by
and may return a value to other code.
This is analogous to procedures or sub-routines
in other programming languages.
Functions allow you to generalize and modularize your code
by creating containers for logical subsets of code
and by allowing code to be reused.
Arguments are passed to functions by value.
So when you call a function and pass a variable,
the value and type of the variable is what's passed
to the function.
If the function then changes that value,
the caller's copy remains unchanged.
For example, here we have a variable I with the value seven.
This variable is passed to a function, F.
After the function returns, we print the value.
The function F takes that value and assigns
it to a local variable named A.
But this is absolutely a different value.
It's in a different scope and is separate in every way.
So when A is incremented in the function,
only its local copy is affected.
The caller's copy remains unchanged,
and printf will print the number seven.
The alternative to call by value is call by reference.
To implement call by reference,
you must do so explicitly.
You will know by reading the code
that a reference is being passed,
and there may be side effects.
In this example, the ampersand
and the function call parameter means you pass
a pointer to I instead of the value of I.
The ampersand is called the reference operator
or sometimes the address of operator.
In the function, the variable P carries
as its value, a pointer to I.
So when we want to increment the value of I,
we do so by de-referencing the pointer.
The asterisk is called the pointer de-reference operator.
By passing a pointer, we explicitly call by reference.
Technically, it's still called by value,
except in this case, the value is the pointer.
The value and the callers variable I will be incremented,
and the printf will print the number eight.
In C++, you may also use the reference type
to implement call by reference.
This makes call by reference appear more implicit.
This is very common in C++,
and it carries some inherent dangers
if not implemented carefully.
In C++, functions are identified
by their function's signature.
This function, which returns the volume of a qvoid
is different from this function
which returns the volume of a sphere,
even though the two functions have the same name.
The return type, the name of the function,
and the types of the function arguments
are all combined to form the function's signature.
The full function signature, not just the name,
is used to identify the function.
Understanding functions is fundamental to C++.
Even with its object-oriented programming model,
functions are the basics of class methods.
All code in C++ happens in functions.