Skip to main content

Cube of int, float, double by overloading

Short answer

Overload cube() for int, float, and double, each returning x*x*x. Call with appropriate types; e.g., cube(3) → 27, cube(2.5f) → 15.625, cube(1.5) → 3.375. Use f suffix for float literal to call float version.

Write a program to calculate and display the cube of integer, float and double number using function overloading (passing single argument to function).

Function overloading: three functions named cube with the same single parameter position but different types. The compiler selects the one matching the argument type.

#include <iostream>
using namespace std;

int cube(int x)
{
    return x * x * x;
}
float cube(float x)
{
    return x * x * x;
}
double cube(double x)
{
    return x * x * x;
}

int main()
{
    int i = 3;
    float f = 2.5f;
    double d = 1.5;

    cout << "Cube of int    " << i << " = " << cube(i) << endl;
    cout << "Cube of float  " << f << " = " << cube(f) << endl;
    cout << "Cube of double " << d << " = " << cube(d) << endl;
    return 0;
}

Output

Cube of int    3 = 27
Cube of float  2.5 = 15.625
Cube of double 1.5 = 3.375

Note: a literal such as 2.5 is a double, so use the f suffix (2.5f) or a float variable to call the float version.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 3 questions →