C++ member function virtual override and overload at the same time

前端 未结 3 678
忘了有多久
忘了有多久 2020-12-13 04:26

If I have a code like this:

struct A {
  virtual void f(int) {}
  virtual void f(void*) {}
};

struct B : public A {
  void f(int) {}
};

struct C : public B         


        
3条回答
  •  青春惊慌失措
    2020-12-13 04:58

    The short answer is "because that's how overload resolution works in C++".

    The compiler searches for functions F inside the C class, and if it finds any, it stops the search, and tries to pick a candidate among those. It only looks inside base classes if no matching functions were found in the derived class.

    However, you can explicitly introduce the base class functions into the derived class' namespace:

    struct C : public B {
      void f(void*) {}
      using B::f; // Add B's f function to C's namespace, allowing it to participate in overload resolution
    };
    

提交回复
热议问题