Home > Net >  Accessing overloaded method from a parent class
Accessing overloaded method from a parent class

Time:09-23

I have stumbled upon this code, and I can't understand, why do I need to specify the class I want to call the method with one argument from? What's more interesting, if I remove the second overloaded method with two parameters, everything will work fine.

class A {
public:
    virtual void foo(int a) const final {};
    virtual void foo(int a, int b) const = 0;
};

class B : public A {
public:
    void foo(int a, int b) const override {}
};

int main() {
    B b;
    b.A::foo(1); // Why do I need to specify A::foo??
    // b.foo(1) -- won't compile
}

CodePudding user response:

It is because when you override foo in B, the other overloads foo from base A are masked. It is a feature of language.

CodePudding user response:

Because what b sees is the overloaded instance of foo(int a, int b), which preforms name hiding, therefore foo(int a, int b) makes foo(int a) invisible from b. If you want to make foo(int a), you should specify that it should look in class A, that's why you need A::

  • Related