1

I have a base class with a virtual fonction foo(int i) and foo() (same name, not same arguments).
The derived class override only foo().
Now the derived class doesn't knows foo(int i) anymore.

class Base
{
public:
  virtual void foo(int i) {
    std::cout << "Base::foo(int i)" << std::endl;
  }
  virtual void foo() {
    std::cout << "Base::foo()" << std::endl;
  };
};

class Derived : public Base
{
public:
  void foo() override {
    std::cout << "Derived::foo()" << std::endl;
  }
};


int main(const int ac, const char* const av[])
{
  Base base;
  base.foo();
  base.foo(42);

  Derived derived;
  derived.foo();
  derived.foo(42);//ERROR : Function unknown
}

Should output :

Base::foo()
Base::foo(int i)
Derived::foo()
Base::foo(int i)

Where does the problem come from and what would be the solutions?
The derived class will sometimes override foo(), sometimes foo(int i) and sometimes both.

Note

If I go through the base class it works, but this solution is not ideal in my program :

Derived derived;
Base* pBase = &derived;
pBase->foo();
pBase->foo(42); //WORK

Edit

Okay, I found on geeksforgeeks.org that you need to use using Base::foo; in derivate class to import other foo functions.
Someone know why and what's going one in the backgourd? I don't like to not understand somethings.

1 Answers1

1

Just add a using declaration inside derived class as shown below. In particular, a using declaration for a base-class member function (like foo) adds all the overloaded instances of that function to the scope of the derived class. Now you can override the version that takes an argument of type int and use the implementation of others that were added in the derived class' scope using the using declaration.

class Derived : public Base
{
public:
   //added this using declaration
   using Base::foo;
  void foo() override {
    std::cout << "Derived::foo()" << std::endl;
  }
};

Working demo The output of the above modified program is as you wanted:

Base::foo()
Base::foo(int i)
Derived::foo()
Base::foo(int i)
Jason
  • 36,170
  • 5
  • 26
  • 60