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.
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)*);
andint 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.
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