Skip to main content

Default argument and overloading program

Short answer

The program shows default arguments, as in float volume(float l, float b=2, float h=3), replace multiple overloaded functions by accepting 1–3 arguments. Overloaded area functions handle circle and rectangle separately. Mixing defaults with overloading can create ambiguous calls.

Write a program to show the relation between default argument and function overloading.

Both default arguments and function overloading let one function name be called with different numbers of arguments. They can conflict: if an overloaded function can be matched with or without the defaulted argument, the call is ambiguous and the compiler reports an error. So overloads and defaults must be designed so that each call has exactly one best match.

Program

#include <iostream>
using namespace std;

// overloaded versions of area
float area(float r)                  // circle
{
    return 3.14159 * r * r;
}
float area(float l, float b)         // rectangle
{
    return l * b;
}
// function with default arguments (box volume)
float volume(float l, float b = 2, float h = 3)
{
    return l * b * h;
}
// ambiguous if declared along with volume(float):
// float volume(float l);

int main()
{
    cout << "Circle area = " << area(2.0f) << endl;
    cout << "Rectangle area = " << area(4.0f, 5.0f) << endl;
    cout << "Volume(1 arg) = " << volume(1) << endl;
    cout << "Volume(2 args) = " << volume(1, 4) << endl;
    cout << "Volume(3 args) = " << volume(1, 4, 5) << endl;
    return 0;
}

Output

Circle area = 12.5664
Rectangle area = 20
Volume(1 arg) = 6
Volume(2 args) = 12
Volume(3 args) = 20

Relation

  • Overloading: different functions, same name, different parameter lists.
  • Default argument: one function, usable with fewer arguments.
  • If we also wrote float volume(float l);, the call volume(1) would match both versions, giving an ambiguity error.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 3 questions →