71

While writing the following function abs, I get the error:

non-member function unsigned int abs(const T&) cannot have cv-qualifier.

template<typename T>
inline unsigned int abs(const T& t) const
{
    return t>0?t:-t;
}

After removing the const qualifier for the function there is no error. Since I am not modifying t inside the function the above code should have compiled. I am wondering why I got the error?

A. K.
  • 34,395
  • 15
  • 52
  • 89

4 Answers4

136

Your desire not to modify t is expressed in const T& t. The ending const specifies that you will not modify any member variable of the class abs belongs to.

Since there is no class where this function belongs to, you get an error.

0009laH
  • 1,960
  • 13
  • 27
Attila
  • 28,265
  • 3
  • 46
  • 55
  • https://stackoverflow.com/a/10982687/4809254 answer seems to be more accurate as in function add say `int add(const int a, const int b)`, we can't have const qualifier with this, as it is not a member function – Vikram Ojha Feb 02 '22 at 07:27
  • 1
    @VikramOjha There are two kinds of `const`s in play in the question (one modifying the `this` pointer if/when the function is a member of a class; and the other one modifying the function parameter). I believe both my answer and Bo's (the one you linked to) explains the cause of the problem the OP had, just worded differently. BTW, the question mentions a function named `abs` with one parameter, not `add` with two, so I'm not sure where that came from in your comment – Attila Feb 04 '22 at 06:11
40

The const modifier at the end of the function declaration applies to the hidden this parameter for member functions.

As this is a free function, there is no this and that modifier is not needed.

The t parameter already has its own const in the parameter list.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
16

The cv-qualifier on a member function specifies that the this pointer is to have indirected type const (or volatile, const volatile) and that therefore the member function can be called on instances with that qualification.

Free functions (and class static functions) don't have a this pointer.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
3

As we all know, const keyword followed after the argument list indicates that this is a pointer to a pointer constant.

There is a non-member function, it does not belong to the class, so add const opposite end error occurs.

Solution to the problem: is to either become a class member function or remove the const keyword const opposite end

DhruvJoshi
  • 17,041
  • 6
  • 41
  • 60