lundi 12 août 2019

Base class methods are not inherited if the child overrides another method with the same name and different signature

First, I apologize for the vague title of the question. Consider the following example:

class A {
    public:
        virtual void foo() const = 0;
        void foo(int n) const {
            while(n--)
                foo();
        }
};

class B: public A {
    public:
        void foo() const override {
            std::cout << "B::foo()" << std::endl;
        }
};

int main() {
    auto obj = B{};

    obj.foo();

    obj.foo(10);
}

Basically I want to have two versions of the method foo in class A (and any child class). The one without argument has to be defined by the child (hence it it declared as pure). But, the one with an integer does not need to be redefined by every child (as the functionality is the same: call the no-argument version n times.)

However the above code does not compile, giving the following error:

g++ -D_GLIBCXX_DEBUG -std=c++11    example.cpp   -o example
example.cpp: In function ‘int main()’:
example.cpp:31:15: error: no matching function for call to ‘B::foo(int)’
   31 |     obj.foo(10);
      |               ^
example.cpp:21:14: note: candidate: ‘virtual void B::foo() const’
   21 |         void foo() const override {
      |              ^~~
example.cpp:21:14: note:   candidate expects 0 arguments, 1 provided

Why this happens? What is wrong in my reasoning? For example if I rename the method with signature int foo(int) to something like int foo2(int)' and then callfoo2` from the child everything works fine.

Aucun commentaire:

Enregistrer un commentaire