Skip to main content

Function overloading; new/delete average program

Short answer

Function overloading: same name, different parameters. For average: int *a = new int[n]; sum values, cast to float: avg = (float)sum/n; delete[] a. Default arguments: assign right to left, specify once, no skipping middle; e.g., void show(int a, int b=5, int c=10); show(1) uses b=5, c=10.

What is function overloading? Use new and delete operators to store n numbers dynamically and find their average using casting operator. What are the things we should remember while using default argument? Explain with an example.

Function overloading

Function overloading means using the same function name for several functions that differ in the number, type or order of their parameters. The compiler selects the correct one at compile time from the arguments of the call (compile-time polymorphism). The return type alone cannot distinguish overloads.

int add(int a, int b);
float add(float a, float b);
int add(int a, int b, int c);

Program: n numbers with new and delete, average with cast

#include <iostream>
using namespace std;

int main()
{
    int n;
    cout << "How many numbers? ";
    cin >> n;

    int *a = new int[n];           // allocate dynamically
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        cout << "Enter number " << i + 1 << ": ";
        cin >> a[i];
        sum += a[i];
    }

    // cast sum to float so the division is not integer division
    float avg = (float)sum / n;
    cout << "Average = " << avg << endl;

    delete[] a;                    // free memory
    return 0;
}

Without the cast, sum / n of two ints would drop the fractional part (e.g. 7/2 = 3). (float)sum makes the division floating point (3.5).

Things to remember with default arguments

  1. Defaults are assigned from right to left; a parameter after a defaulted one must also have a default.
  2. Specify the default only once (in the prototype, or the definition if no prototype).
  3. Defaults can be constants or expressions but not local variables.
  4. Avoid ambiguity with overloaded functions.
  5. Arguments are matched left to right; we cannot skip a middle argument.
void show(int a, int b = 5, int c = 10);
show(1);        // b = 5, c = 10
show(1, 2);     // c = 10
show(1, 2, 3);  // no defaults

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 3 questions →