1

I am learning overloading an inline function.

In testing this code I can't compile with the following errors I can't understand as to what's wrong.

I tested it with only 1 inline function and works but a second breaks it. Can you please share some guidance:

Thank you for your help, Sergio

Compiler errors:

  • abs exception specification does not match previous declaration line 13
  • function long abs (const long) throw() already has body line 13
  • abs redefinition; different exception specification line 19
  • abs error in function definition or declaration; function not called line 30
  • abs error in function definition or declaration; function not called line 32

#include "pch.h"
#include <iostream>
using namespace std;

// Overload abs() three ways
inline int abs(int n)
{
    cout << "In integer abs() \n";
    return((n < 0) ? -n : n);
}

inline long abs(long n)
{
    cout << "In long abs() \n";
    return((n < 0) ? -n : n);
}


inline double abs(double n) {
    cout << "In double abs() \n";
    return ((n < 0 ? -n : n));
}


int main()
{
    cout << "Absolute value of -10 Is ";
    cout << abs(-10) << "\n";
    cout << "Absolute value of -10L Is ";
    cout << abs(-10L) << "\n";
    cout << "Absolute value of -10.01 Is ";
    cout << abs(-10.01) << "\n";
}
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
Sergio Solorzano
  • 476
  • 9
  • 29

2 Answers2

5

Your error is here:

using namespace std;

since this brings into the global namespace the definitions of the function overloads std::abs() (they are declared & defined in cmath which appears to be #included directly or indirectly into iostream), which then clash with your own definitions. The above statement (using namespace std;) is almost never a good idea, certainly not in a header file -- it is, unfortunately, commonly used in online coding contests to simplify code (no need for std::).

Btw, this has only do with inline inasmuch as the function definitions (not the declarations) clash, which must be declared inline in header files to obtain the proper linkage.

Walter
  • 44,150
  • 20
  • 113
  • 196
3

Precense of using namespace std; causes a conflict with ::std::abs function. However getting rid of using namespace std; will not solve the issue complitely.

The primary problem here is the use of a non-unique name for a function in global namespace. abs is a function from C standard library therefore you should not use this name for your own functions. Otherwise your may get an error if <stdlib.h> is included somewhere, or even a random Undefined Behavior because of ODR violation.

In order to prevent name conflicts in C++ you should typically define new functions in custom namespace:

n_sergio_solorzano_stuff
{
    // Overload abs() three ways
    inline int abs(int n)
    {
    ...

or select globally unique names when you need to add something into global namespace:

inline int sergio_solorzano_stuff_abs(int n)
user7860670
  • 35,849
  • 4
  • 58
  • 84