0

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.

Nick
  • 9,962
  • 4
  • 42
  • 80

1 Answers1

4

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 consts 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?

Community
  • 1
  • 1
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Might be worth explaining what "top level" means here. I get it, you get it, but the OP may not understand the distinction when comparing `int const*` to `int const&` to `int const` and how this relates to the actual reasoning for the rule (which is pointlessness of `const` on an object passed by value, at least in the original declaration). – Lightness Races in Orbit Aug 11 '15 at 13:42
  • 1
    @LightnessRacesinOrbit Good point. I added a link to a related SO post. – juanchopanza Aug 11 '15 at 13:48