Skip to main content

Default arguments and function overloading

Short answer

Default arguments provide values for trailing parameters if omitted, allowing one function to handle multiple argument counts. E.g., int volume(int l, int w=1, int h=1) works as three overloaded functions. Overloading permits separate implementations, while defaults share one body; mixing can cause ambiguous calls.

Explain how default arguments are used with functions. How can a function with default argument be implemented with function overloading? Explain with example.

Default arguments

A default argument is a value given in the function declaration that is used automatically when the caller does not supply that argument. Default values are given from the right side: once a parameter has a default, all parameters to its right must also have defaults.

float simpleInterest(float p, float t, float r = 5.0);   // r defaults to 5

simpleInterest(1000, 2);        // r = 5.0 is used
simpleInterest(1000, 2, 8);     // r = 8, default ignored

Advantages: fewer arguments to write, one function covers common cases, and existing calls keep working when a new parameter is added.

Default arguments and function overloading

A function with default arguments behaves like a set of overloaded functions. The same effect is obtained by writing several functions with the same name and different parameter lists.

#include <iostream>
using namespace std;

// Version 1: using default arguments
int volume1(int l, int w = 1, int h = 1) {
    return l * w * h;
}

// Version 2: using function overloading (same behaviour)
int volume2(int l)               { return l; }
int volume2(int l, int w)        { return l * w; }
int volume2(int l, int w, int h) { return l * w * h; }

int main() {
    cout << volume1(5) << " " << volume1(5, 4) << " " << volume1(5, 4, 3) << endl;
    cout << volume2(5) << " " << volume2(5, 4) << " " << volume2(5, 4, 3) << endl;
    return 0;
}

Output

5 20 60
5 20 60

The single function volume1 replaces the three overloaded functions of volume2.

Caution (ambiguity): if overloaded functions and default arguments are mixed carelessly, calls can become ambiguous. For example, with void f(int a, int b = 0); and void f(int a);, the call f(5) matches both and the compiler reports an error.

Default argumentsFunction overloading
One function bodySeparate body for each version
Same logic with some values optionalDifferent logic allowed for each version
Defaults only at the right endAny differing parameter types or counts

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 3 questions →