Lesson Introduction

In this lesson, we'll dive into function parameters in C++, focusing on default values and references. These concepts help you write more flexible and efficient functions. By the end, you'll know how to set default values for parameters and modify variables directly by passing them by reference.

Default Values in Function Parameters

In C++, you can give function parameters default values. If you don't provide a value when calling the function, the default is used.

Imagine a function that prints a message. Sometimes, you might want to use a default message if none is provided:

#include <iostream>

void displayMessage(std::string message = "Hello, World!") {
    std::cout << message << std::endl;
}

int main() {
    displayMessage();  // Outputs: Hello, World!
    displayMessage("Hi there!");  // Outputs: Hi there!
    return 0;
}

Here, displayMessage has a default value of "Hello, World!" for its message parameter. When displayMessage is called without an argument, it prints the default message. With an argument like "Hi there!", it prints that instead.

Default values make functions flexible, reducing the need for additional function variants.

Potential Pitfalls

In C++, parameters with default values must be defined after any parameters without default values. This is important to ensure the function calls are unambiguous.

Here is an incorrectly defined function with a parameter with a default value appearing before a parameter without a default value:

#include <iostream>

// This will cause a compilation error
void printDetails(std::string country = "Unknown", std::string name, int age) {
    std::cout << "Name: " << name << ", Age: " << age << ", Country: " << country << std::endl;
}

int main() {
    // Compilation will fail
    printDetails("USA", "Alice", 30);
    return 0;
}

In the incorrect example, the compiler will produce an error because it cannot determine how to handle the default parameter if it precedes non-default parameters.

Ensuring that parameters with default values are positioned after any non-default parameters allows the calls to the function to be clear and prevents any ambiguity for the compiler.

Here is a corrected version where the parameter with a default value comes after parameters without defaults:

#include <iostream>

void printDetails(std::string name, int age, std::string country = "Unknown") {
    std::cout << "Name: " << name << ", Age: " << age << ", Country: " << country << std::endl;
}

int main() {
    printDetails("Alice", 30);  // Outputs: Name: Alice, Age: 30, Country: Unknown
    printDetails("Bob", 25, "USA");  // Outputs: Name: Bob, Age: 25, Country: USA
    return 0;
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal