Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non-member function cannot have cv-qualifier

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?

like image 905
A. K. Avatar asked Jun 11 '12 14:06

A. K.


People also ask

What are non member functions?

Non-member Function: The function which is declared outside the class is known as the non-member function of that class. Below is the difference between the two: The member function can appear outside of the class body (for instance, in the implementation file).

What is CV in C++?

c in cv means const and v means volatile. From the C++ Standard (3.9.3 CV-qualifiers) The term object type (1.8) includes the cv-qualifiers specified in the decl-specifier-seq (7.1), declarator (Clause 8), type-id (8.1), or newtype - id (5.3. 4) when the object is created.


2 Answers

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.

like image 101
Attila Avatar answered Sep 21 '22 10:09

Attila


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.

like image 32
Bo Persson Avatar answered Sep 23 '22 10:09

Bo Persson