BeginnerLesson 5 of 18
Functions, Overloading and Declarations – C++
Defining functions, default arguments, overloading and multiple return values.
A function has a return type, a name and a parameter list. Default arguments make parameters optional; overloading allows the same name with different parameter types.
#include <iostream>
#include <string>
std::string begruesse(const std::string& name, const std::string& gruss = "Hello") {
return gruss + ", " + name + "!";
}
int quadrat(int x) { return x * x; }
double quadrat(double x) { return x * x; } // overload
int main() {
std::cout << begruesse("Ada") << '\n';
std::cout << begruesse("Linus", "Hey") << '\n';
std::cout << quadrat(4) << " " << quadrat(1.5) << '\n'; // 16 2.25
}A function must be declared before it is used. That is why larger projects separate the declaration (header .hpp) from the definition (.cpp). constexpr functions can already be evaluated at compile time.
#include <iostream>
int fakultaet(int n); // declaration (prototype)
constexpr int kubik(int x) { return x * x * x; }
static_assert(kubik(3) == 27); // check at compile time
int main() {
std::cout << fakultaet(5) << '\n'; // 120
}
int fakultaet(int n) { // definition
return n <= 1 ? 1 : n * fakultaet(n - 1);
}The easiest way to return multiple values is as a std::pair, std::tuple or your own struct, and you unpack them with structured bindings:
#include <iostream>
#include <utility>
std::pair<int, int> teile(int a, int b) { return {a / b, a % b}; }
int main() {
auto [quotient, rest] = teile(17, 5);
std::cout << quotient << " Rest " << rest << '\n'; // 3 Rest 2
}TipMark functions whose result must not be ignored with
[[nodiscard]]. The compiler then warns if someone discards the return value.