C++
Beginner
1 min read
Functions, Overloading, and Default Arguments
Example
#include <iostream>
#include <string>
// Overloaded print functions
void print(int value) {
std::cout << "int: " << value << "\n";
}
void print(double value) {
std::cout << "double: " << value << "\n";
}
void print(const std::string& value) {
std::cout << "string: " << value << "\n";
}
// Default arguments — defaults only in declaration
void connect(const std::string& host,
int port = 443,
bool secure = true) {
std::cout << (secure ? "https" : "http")
<< "://" << host << ":" << port << "\n";
}
// Inline helper
inline int square(int n) { return n * n; }
int main() {
print(42);
print(3.14);
print(std::string("overload"));
connect("example.com"); // uses defaults
connect("example.com", 8080); // overrides port
connect("example.com", 80, false); // overrides both
std::cout << "square(7) = " << square(7) << "\n";
return 0;
}