Often we need to pass data to a function. Think about your C# class when you called: MessageBox.Show()
. You needed to pass a string into the method so it would show something, otherwise what's the point? Let's look at how to pass data to functions in C++. I'll give you a hint: it's the same way.
Default Parameters and Function Overloading
In many languages, C++ included, you can provide a default value to a parameter so it doesn't need to be passed manually. Take a look.
In most programming languages you can overload functions. This just means that you can have multiple functions (or methods) with the same name. Let's see how it's done.
Passing Data by Reference
Sometimes we need a function to modify variables that exist outside of the function. In the next video, I'll cover an example that you should be familiar with from C# Intro.
Now that you get the concept, let's do an example in C++.
Review Questions
The following are examples of questions similar to what you can expect to see on the next exam.
- How many parameters can a function have? As many as you want.
-
What is the difference between passing a variable by value and by reference?
By value means the value of the variable is coppied.
By reference means that the original variable (in memory) is referenced. - What would you add to an argument to make it by reference? An ampersand (after the data type, before the name).
- What is function overloading? Having two functions with the same name (but different signatures).
- If you have a prototyped function, where would a default parameter go? In the prototype.
Above and Beyond
The content past here is related, but beyond the scope of the class. In other words, you will not be tested on this!
Caveat with Default Parameters
Using default paramters can take some getting used to, as they have some odd quirks. One of these is the placement of the default vaules, as shown here.