Default Arguments
Overview
Sometimes a function has parameters that are almost always the same value. For example, a connectToServer(string ip, int port) function might use port 8080 99% of the time.
Instead of forcing the developer to type 8080 every single time they call it, C++ allows you to define Default Arguments. If the caller provides a value, it uses their value. If the caller omits the value, the compiler automatically injects the default value. This drastically reduces boilerplate code.
Syntax
#include <iostream>
#include <string>
// 'port' defaults to 8080 if not provided!
void connect(std::string ip, int port = 8080) {
std::cout << "Connecting to " << ip << " on port " << port << "\n";
}
int main() {
// 1. Using the default argument
connect("192.168.1.1"); // Connects to port 8080
// 2. Overriding the default argument
connect("10.0.0.5", 443); // Connects to port 443
return 0;
}Common Pitfalls
- Placing default arguments on the left side. In C++, default arguments MUST be positioned at the absolute far right of the parameter list. You cannot write
void func(int a = 5, int b). The compiler wouldn't know iffunc(10)was meant for 'a' or 'b'. It must bevoid func(int a, int b = 5). - Defining defaults in both the Header and the CPP file. If you declare the default argument in the function prototype (
.hfile), you CANNOT redefine it in the function body (.cppfile). Doing so causes a 'redefinition of default argument' compiler error.
Interview Questions
When a C++ function is called, arguments are resolved strictly positionally from left to right. If a default parameter was allowed in the middle, calling func(A, B) would create insurmountable ambiguity. The compiler wouldn't know whether to apply B to the middle parameter or skip it and apply it to the final parameter.
Real-World Example
Using default arguments in a Logging function to simplify standard warnings while allowing strict overrides for fatal errors.
#include <iostream>
#include <string>
void logMessage(std::string message, bool isError = false, int errorCode = 0) {
if (isError) {
std::cout << "[ERROR " << errorCode << "] " << message << "\n";
} else {
std::cout << "[INFO] " << message << "\n";
}
}
int main() {
// Clean, standard call
logMessage("System booted successfully.");
// Overriding the defaults for an emergency
logMessage("Database connection lost!", true, 503);
return 0;
}Check Your Knowledge
Test your understanding of Default Arguments with these quick questions.