Skip to Content
FunctionsDefault Parameters

Default Parameters in C++ Functions

Default parameters allow you to provide default values for function parameters. If the caller doesn’t provide a value, the default is used.

Basic Syntax

returnType functionName(type param1 = defaultValue) { // function body }

Simple Example

#include <iostream> using namespace std; void greet(string name = "Guest") { cout << "Hello, " << name << "!" << endl; } int main() { greet("Alice"); // Uses "Alice" greet(); // Uses default "Guest" return 0; }

Output:

Hello, Alice! Hello, Guest!

How It Works

When you call greet() without arguments:

  • The function uses the default value “Guest”

When you call greet("Alice"):

  • The provided value “Alice” overrides the default

Multiple Default Parameters

You can have multiple parameters with defaults:

#include <iostream> using namespace std; void displayInfo(string name = "Unknown", int age = 0, string city = "Not specified") { cout << "Name: " << name << endl; cout << "Age: " << age << endl; cout << "City: " << city << endl; cout << "---" << endl; } int main() { displayInfo("Alice", 25, "New York"); displayInfo("Bob", 30); displayInfo("Charlie"); displayInfo(); return 0; }

Output:

Name: Alice Age: 25 City: New York --- Name: Bob Age: 30 City: Not specified --- Name: Charlie Age: 0 City: Not specified --- Name: Unknown Age: 0 City: Not specified ---

Important Rule: Right-to-Left

Default parameters must be specified from right to left. Once a parameter has a default, all following parameters must also have defaults.

✅ Correct

void function1(int a, int b = 10, int c = 20); // ✓ void function2(int a = 5, int b = 10, int c = 20); // ✓ void function3(string text, int count = 1); // ✓

❌ Wrong

void function4(int a = 5, int b, int c = 20); // ✗ Error: b has no default void function5(int a = 5, int b); // ✗ Error: a has default but b doesn't

Practical Example: Power Function

#include <iostream> #include <cmath> using namespace std; // Calculate power with default exponent of 2 (square) double power(double base, int exponent = 2) { return pow(base, exponent); } int main() { cout << "5^3 = " << power(5, 3) << endl; // 125 cout << "4^2 = " << power(4) << endl; // 16 (default exponent) cout << "7^2 = " << power(7) << endl; // 49 (default exponent) return 0; }

Output:

5^3 = 125 4^2 = 16 7^2 = 49

Rectangle Area with Default Square

#include <iostream> using namespace std; // If height not provided, assumes it's a square double calculateArea(double width, double height = -1) { if (height == -1) { height = width; // Make it a square } return width * height; } int main() { cout << "Rectangle 5x3: " << calculateArea(5, 3) << endl; cout << "Square 4x4: " << calculateArea(4) << endl; return 0; }

Output:

Rectangle 5x3: 15 Square 4x4: 16

Printing with Default Separator

#include <iostream> #include <string> using namespace std; void printWithSeparator(string text, char separator = '-', int count = 20) { for (int i = 0; i < count; i++) { cout << separator; } cout << endl << text << endl; for (int i = 0; i < count; i++) { cout << separator; } cout << endl; } int main() { printWithSeparator("Title 1"); printWithSeparator("Title 2", '*'); printWithSeparator("Title 3", '=', 30); return 0; }

Output:

-------------------- Title 1 -------------------- ******************** Title 2 ******************** ============================== Title 3 ==============================

Interest Calculator

#include <iostream> using namespace std; // Calculate simple interest with default rate of 5% double calculateInterest(double principal, double time, double rate = 5.0) { return (principal * time * rate) / 100; } int main() { cout << "Interest on $1000 for 2 years at 5%: $" << calculateInterest(1000, 2) << endl; cout << "Interest on $1000 for 2 years at 7%: $" << calculateInterest(1000, 2, 7.0) << endl; return 0; }

Output:

Interest on $1000 for 2 years at 5%: $100 Interest on $1000 for 2 years at 7%: $140

Array Printer with Default Separator

#include <iostream> using namespace std; void printArray(int arr[], int size, string separator = ", ") { for (int i = 0; i < size; i++) { cout << arr[i]; if (i < size - 1) { cout << separator; } } cout << endl; } int main() { int numbers[] = {1, 2, 3, 4, 5}; cout << "With default separator: "; printArray(numbers, 5); cout << "With custom separator: "; printArray(numbers, 5, " | "); return 0; }

Output:

With default separator: 1, 2, 3, 4, 5 With custom separator: 1 | 2 | 3 | 4 | 5

Logger Function

#include <iostream> #include <string> using namespace std; void log(string message, string level = "INFO") { cout << "[" << level << "] " << message << endl; } int main() { log("Application started"); log("User logged in", "DEBUG"); log("Database error", "ERROR"); log("Processing data"); return 0; }

Output:

[INFO] Application started [DEBUG] User logged in [ERROR] Database error [INFO] Processing data

Function Overloading vs Default Parameters

You can achieve similar results with either approach:

Using Default Parameters

void display(int value, bool newline = true) { cout << value; if (newline) cout << endl; }

Using Function Overloading

void display(int value) { cout << value << endl; } void display(int value, bool newline) { cout << value; if (newline) cout << endl; }

Note: Default parameters are usually simpler and more maintainable.

Best Practices

  1. Use sensible defaults: Choose defaults that cover the most common use case
  2. Document default values: Make it clear in comments what the defaults are
  3. Consider const references for complex default objects:
    void process(const string& text = "default");
  4. Don’t overuse: Too many defaults can make code hard to understand
  5. Put required parameters first: This makes the function signature clearer

Common Mistakes

Default in Declaration AND Definition

// Wrong: default specified in both places void greet(string name = "Guest"); // Declaration void greet(string name = "Guest") { // Definition - Error! cout << "Hello, " << name << endl; } // Correct: default only in declaration void greet(string name = "Guest"); // Declaration void greet(string name) { // Definition cout << "Hello, " << name << endl; }

Skipping Parameters

void display(int a, int b = 10, int c = 20); // You cannot skip b and provide c // display(5, , 30); // ✗ Syntax error // You must provide parameters in order display(5); // ✓ Uses defaults for b and c display(5, 15); // ✓ Uses default for c display(5, 15, 30); // ✓ All provided

Practice Exercises

  1. Greeting Function: Create a function that greets a user with optional time of day (default: “day”).

  2. Temperature Display: Write a function that displays temperature with optional unit (default: “C”).

  3. Draw Rectangle: Create a function that draws a rectangle with optional fill character (default: ’*’).

  4. Calculate Discount: Write a function that calculates price after discount (default: 10%).

  5. Format Phone Number: Create a function that formats phone numbers with optional country code (default: “+1”).

When to Use Default Parameters

Good use cases:

  • Common default configurations
  • Optional formatting options
  • Backward compatibility
  • Sensible fallback values

Avoid when:

  • The “default” isn’t obvious
  • Most calls need to override the default
  • The default value might change frequently

Next Steps

  • Learn about function overloading to create multiple versions with different parameters
  • Explore templates for generic function parameters
  • Study reference parameters for efficient data passing

Default parameters make your functions more flexible and easier to use!

Last updated on