Title kind of says it all. I can't figure out why the compiler will allow this:
#include <iostream>
class Base
{
public:
Base() = default;
virtual ~Base() {}
virtual void set(const int a) = 0;
};
class Derived : public Base
{
public:
Derived() = default;
virtual ~Derived() {}
void set(int a) override <-------const tossed out
{
a = 2;
std::cout << "In derived set" << std::endl;
my_a = a;
}
int my_a = 0;
};
int main()
{
Derived d;
d.set(4);
}
I understand that functionally, const int a and int a are copies - but why is the const ignored as part of the signature?
The compiler (rightfully) complains about this:
void test1(int a)
{
a = 2;
}
void test2(const int a)
{
a = 2; <------ compile error
}
So why does the override pass and basically allow me to do the same thing in the derived class? Why is const not part of the signature for override verification?
Probably a stupid question - but I can't figure out why.
Thanks!
Top-level
conston a function parameter in a function declaration that is not a definition has no meaning at all, just like the name of such a parameter. It is not part of the function's type or signature.This is so because such a
constcan only possibly have a meaning for a specific definition. It has no meaning for a caller, for whom declarations are written. At the call site there is no difference in whether or not the function parameter is top-levelconst.So
is 100% equivalent to
as it is also for any other function. No matter whether the function parameter is
constin the declaration, it can always be or not be top-levelconstin a definition.For example:
or:
As a consequence, top-level
constis also ignored when determining virtual function overrides.