1

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
}

  • "if I remove the second overloaded method with two parameters" what exactly do you mean? If you remove `A::foo` then `B` breaks, because `B::foo` is declared as `override`. Instead of describing what to modify on the code, better show the modified code – 463035818_is_not_an_ai Sep 22 '21 at 14:25
  • Having a method in a child class with the same name as method in parent class *shadows* all the methods from parent class. You can add `using A::foo();` in `B` class to bring them back. – Yksisarvinen Sep 22 '21 at 14:26
  • Probably duplicate: [overloading base class method in derived class](https://stackoverflow.com/questions/16835897/overloading-base-class-method-in-derived-class) – Yksisarvinen Sep 22 '21 at 14:28
  • Overloading only applies to names defined in the same scope. There is only one `foo` defined in `B`, so calling it with a single argument is an error. – Pete Becker Sep 22 '21 at 14:31
  • @463035818_is_not_a_number What I mean is that if I remove foo(int, int) from both class A and class B, then the code will be compiled if we uncomment the last line – JungleTryne Sep 22 '21 at 14:53

2 Answers2

0

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

Jarek C
  • 1,077
  • 6
  • 18
0

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::

Karen Baghdasaryan
  • 2,407
  • 6
  • 24