Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does overriding a method and adding const to a parameter type work? [duplicate]

Tags:

c++

Consider the following example:

#include <iostream>
#include <string>

class Base {
public:
    virtual void func(int a) {}
};

class Derived : public Base {
    public:
    void func( const int a) override {
    }
};


int main()
{
    Derived d;
    d.func(1);

    return 1;
}

I override the func method but add const to the parameter, in which case the linker should scream that something is wrong. Either the function is not overridden or the function parameter should not be const.

But to my surprise, this code links and works.

You can find an online example here.

Am I missing something? Why does this code work?

Although similar to Functions with const arguments and Overloading it addresses a different problem. That question was about not being possible to overload a method of the base class, while this question addresses the problem of being able to override a derived method.

like image 739
Izzy Avatar asked Jun 19 '19 07:06

Izzy


1 Answers

Because their signatures are the same in fact.

The type of each function parameter in the parameter list is determined according to the following rules:

...

4) Top-level cv-qualifiers are dropped from the parameter type (This adjustment only affects the function type, but doesn't modify the property of the parameter: int f(const int p, decltype(p)*); and int f(int, const int*); declare the same function)

That means, void func(int a) and void func(const int a) are considered as the same function type; then the overriding is valid.

like image 171
songyuanyao Avatar answered Oct 22 '22 04:10

songyuanyao