Summary - Functions
- C++ course
- Beginner
- Lesson 70/116
- 5 min
Combine overloading and default parameters to write a math helper class.
Summary: Functions
In this group you learned C++ functions. The definition void greet() { ... } creates a function; the call greet(); runs it. The signature is return type + name + parameter list.
Functions that return a value send a result back with return; void only performs a side effect. Parameters are copied by value. Sharing a name with different parameters is overloading; giving parameters a default value is the default parameter feature. These are the foundations of breaking code into reusable pieces.
Practice Write a square function
Define an int square(int x) function that returns x * x. In main, call square(7) and print the result.
Starter code
#include <iostream>
// Define square
int main() {
// Print square(7)
return 0;
}Sample solution
#include <iostream>
int square(int x) {
return x * x;
}
int main() {
std::cout << square(7) << std::endl;
return 0;
}Expected output
49
Practice Sum with overloads
Define two add overloads: int add(int a, int b) and double add(double a, double b). In main, call both and print the results separated by a space.
Starter code
#include <iostream>
// Define two add overloads (int and double)
int main() {
// Print both add calls (integer and decimal)
return 0;
}Sample solution
#include <iostream>
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int main() {
std::cout << add(2, 3) << " " << add(2.5, 3.5) << std::endl;
return 0;
}Expected output
5 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which of the following is a valid function signature?
// ???- greet
- void greet
- void greet() Correct answer
- greet();
Explanation: return type + name + parameter list is the full signature.
2 Match the concepts
| Term | Meaning |
|---|---|
return |
Returns a value |
void |
Returns nothing |
overloading |
Same name, different parameters |
b = 0 |
Default value |
3 Complete the call
std::cout << add(____, 4) << std::endl;
std::cout << add(3, 4) << std::endl;
Explanation: add(3, 4) first argument 3, second 4.