The args function declared as const became not constant with the definition

Code

class A { public: void f(const int i); }; void A::f(int i) { std::cout<<++i<<std::endl; } int main() { A a; af(1); } 

Why does the compiler not give an error in this case? Why does a definition override a constant argument? In addition, when the argument is of type reference (&) , the compiler throws an error, but why not in this case?

Is there any compiler flag to enable a warning about these mentioned cases?

I'm more interested in the POV compiler error. Because you can easily put a declaration (const) and a definition (mutable) in different ways, and still the compiler accepts it. If a mistake can be made, it will eventually be made. Why can't the compiler complain when there is such a difference.

+5
source share
2 answers

From 11.3.5 Functions [dcl.fct]:

  1. One name can be used for several different functions in one volume; this is an overload of a function (section 16). All declarations for the function must exactly match both the return type and the TypeList parameter. The type of function is determined using the following rules. The type of each parameter (including the function of the parameter packages) is determined from its own pointer-pointer-seq and descriptor. After determining the type of each parameter, any parameter of type "array T" or type of function T, "pointer to T". After creating a list of parameter types of any top-level cv-qualifiers, the change in the parameter type is deleted when forming the function type. The resulting list of converted parameter types and the presence or absence of an ellipse or function. A parameter package is a list of parameter parameters.

This basically means that const int and int interchangeable in the context of your question.

On the other hand, if you add a link, for example const int& , const no longer the top-level cv qualifier (it marks the reference value as const ), so the compiler complains.

Usually const added to the definition to emphasize that the parameter does not change inside the body of the function.

+5
source

Function Declaration

 void f(const T arg); 

coincides with

 void f(T arg); 

but

 void f(const T& arg); 

does not match

 void f(T& arg); 

and

 void f(const T* arg); 

does not match

 void f(T* arg); 

 void f(const T arg); void f(T arg); 

are the same because top-level cv qualifiers are removed for function resolution purposes. There const -ness applies to the top-level type, T

Oto

 void f(const T& arg); void f(T& arg); 

do not match, since const -ness is applied to the object referenced by the arg reference, and not to arg itself, which is just a top-level thing.

+3
source

Source: https://habr.com/ru/post/1275098/


All Articles