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?
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With