Reputation: 10539
Why this is compiled without warning?
struct A{
virtual void get(int const x) = 0;
};
struct B : public A{
virtual void get(int x) override{
}
};
int main(int argc, char *argv[]){
B b;
b.get(6);
return 0;
}
Here is the output:
g++ -std=c++11 -Wall ./x.cc
clang -std=c++11 -Wall ./x.cc -lstdc++
If I add -Wextra
I get messages for unused function parameters, but still nothing about the const.
Upvotes: 0
Views: 207
Reputation: 227370
The method signatures are exactly the same, so there is no problem with the code. If they didn't match, you would expect an error, not a warning.
Why are the signatures the same? Because top level const
s get ignored1. These three are duplicate declarations:
void foo(const int); // declaration of foo(int)
void foo(int const); // re-declaration of foo(int)
void foo(int); // re-declaration of foo(int)
It is best to omit top level const
from function declarations because they are at best confusing. You can use const
in the function definition as an implementation detail, in the same way as you can declare any local variable const
if you don't want it to be modified.
void foo(const int n)
{
// n is const here. I know that is shouldn't be changed so I enforce it.
}
1 See also: What are top-level const
qualifiers?
Upvotes: 4