That we are “blessed” with several absolute value functions is an accident of history. C libraries were already available when C++ arrived; they could be easily used, so they were not rewritten using function overloading. You are to find all the absolute value functions you can, and rewrite all of them overloading the abs function name. At a minimum you should have the int , long , float , and double types represented.
PROGRAM CODE:
// abs_overload.h
#ifndef ABS_OVERLOAD_H
#define ABS_OVERLOAD_H
// Function overloading for int
int abs(int num) {
return (num < 0) ? -num : num;
}
// Function overloading for long
long abs(long num) {
return (num < 0) ? -num : num;
}
// Function overloading for float
float abs(float num) {
return (num < 0.0) ? -num : num;
}
// Function overloading for double
double abs(double num) {
return (num < 0.0) ? -num : num;
}
#endif
//Header section
#include <iostream>
#include "abs_overload.h"
using namespace std;
//main program
int main()
{
//Initilize variables
int num1 = -5;
long num2 = -1234567890L;
float num3 = -3.14f;
double num4 = -2.71828;
//Display the output using abs function
cout << "Absolute value of " << num1 << ": " << abs(num1) << endl;
cout << "Absolute value of " << num2 << ": " << abs(num2) << endl;
cout << "Absolute value of " << num3 << ": " << abs(num3) << endl;
cout << "Absolute value of " << num4 << ": " << abs(num4) << endl;
return 0;
}
OUTPUT OF THE PROGRAM CODE:
Absolute value of -5: 5
Absolute value of -1234567890: 1234567890
Absolute value of -3.14: 3.14
Absolute value of -2.71828: 2.71828