0

Can somebody explain to me why the following code compiles

#include <cmath>

class BaseFunctionClass {
    public:
        virtual double operator()(const double x) const = 0;
        virtual ~BaseFunctionClass() {}
};


class mySin : public BaseFunctionClass {
    public:
        double operator()(double x) const override {
            return std::sin(x);
        }
};

int main(){

    mySin f1;

    return 0;
}

We have the two definitions:

double operator()(const double x) const   //BaseFunctionClass
double operator()(double x) const         //mySin

but shouldn't the override keyword make sure that I can only redefine functions in derived classes that have a virtual counterpart in the base class? Why is the const for the argument ignored?

Sito
  • 494
  • 10
  • 29
  • 2
    Rule: When returning or passing by value, const doesn't matter. – NathanOliver Jan 09 '20 at 17:39
  • 1
    @NathanOliver Minor point: Constness of an argument matters to the definition of the function. – eerorika Jan 09 '20 at 17:43
  • @eerorika Could you maybe elaborate? I don't really see how this goes hand in hand with what is written in the thread mentioned as duplicate.. – Sito Jan 09 '20 at 17:44
  • @Sito It matters *inside* the function. But the signature (i.e. the part of the function that’s visible outside it) is identical. – Konrad Rudolph Jan 09 '20 at 17:45
  • 1
    @Sito You can for example declare `void foo(int);` and then try to define `void foo(int const x) { x = 42; // ill-formed }`. Latter defines the same function as was declared, but the argument cannot be modified within the function because it was const in the argument list of the definition. It doesn't matter to the caller whether the argument is const or not, and it doesn't matter in terms of signature matching, but it matters in the definition. I would personally never use const object arguments. – eerorika Jan 09 '20 at 17:50

0 Answers0