0

I have some questions about inheritance and function overloading. I wrote some interfaces something like below. Now I'm trying to call some function of the parent class from derived class but it doesn't work as I intended.

Why is it possible to call b.hello() but not b.test()?

#include <iostream>

using namespace std;

class A {
public:
    void hello() {}
    void test() {}
    virtual void test(int a) {}
};

class B : public A {
public:
    void test(int a) override {}
};

int main() {
    B b;

    // Is possible to call test(int) through B
    b.test(1);

    // Is not possble to call test() through B
    b.test();

    // But, is possible to call hello() through B
    b.hello();
}
JFMR
  • 23,265
  • 4
  • 52
  • 76
  • What error do you get? What changes have you tried? – nicomp Mar 06 '20 at 14:49
  • when asking about code and error, please show the real code (you have missing `;` which lets me thing that your real code is different) and the error. – 463035818_is_not_an_ai Mar 06 '20 at 14:51
  • Because compiler tries to find `test` function in `B`, and when it finds it there, discovers that you try to call it without parameters. – vahancho Mar 06 '20 at 14:51
  • 1
    Does this answer your question? [c++ issue with function overloading in an inherited class](https://stackoverflow.com/questions/14212190/c-issue-with-function-overloading-in-an-inherited-class) – Algirdas Preidžius Mar 06 '20 at 14:53

1 Answers1

1

Why is it possible to call b.hello() but not b.test()?

There are member functions with the name test in both classes A and B. However, classes are scopes, and functions do not overload across scopes. Therefore, the overloaded set for the function test in B consists only of test(int).

A member function with the name hello is, on the other hand, only present in class A, and B inherits this member function.


Note however that it is still possible to call A::test() on b:

B b;
b.A::test();

You can also bring A::test to the scope introduced by B with the using declaration:

class B: public A {
public:
    using A::test; // brings A::test() to this scope
    void test(int a) override {}
};

Now, A::test() can be called directly on b since the overload set for the function test in B consist of both test() and test(int):

B b;
b.test();  // calls A::test()
b.test(1); // calls B::test(int)
JFMR
  • 23,265
  • 4
  • 52
  • 76