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();
}
4
  • What error do you get? What changes have you tried? Commented Mar 6, 2020 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. Commented Mar 6, 2020 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. Commented Mar 6, 2020 at 14:51
  • 1
    Does this answer your question? c++ issue with function overloading in an inherited class Commented Mar 6, 2020 at 14:53

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments