4

I am confused about compiler errors regarding the code below:

class Base {
public:
  virtual ~Base () { }
  virtual void func () { }
  virtual void func (int) { }
  virtual void another () { }
  virtual void another (int) { }
};

class Derived : public Base {
public:
  void func () { }
};

int main () {
  Derived d;
  d.func();
  d.func(0);
  d.another();
  d.another(0);
}

Using gcc 4.6.3, the above code causes an error at d.func(0) saying that Dervied::func(int) is undefined.

When I also add a definition for func(int) to Derived, then it works. It also works (as in the case of "another") when I define neither func() nor func(int) in Derived.

Clearly there is some rule going on here regarding virtual overloaded functions, but this is the first time I've encountered it, and I don't quite understand it. Can somebody tell me what exactly is going on here?

Jason C
  • 38,729
  • 14
  • 126
  • 182

1 Answers1

11

When you override func() in Derived, this hides func(int).

gcc can warn you about this:

$ g++ -Wall -Woverloaded-virtual test.cpp
test.cpp:5:16: warning: 'virtual void Base::func(int)' was hidden [-Woverloaded-virtual]
test.cpp:12:8: warning:   by 'virtual void Derived::func()' [-Woverloaded-virtual]

You can fix this with using:

class Derived : public Base {
public:
  using Base::func;
  void func () { }
};

For a discussion of why this happens, see Why does an overridden function in the derived class hide other overloads of the base class?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 1
    Hey thanks!! The tip about -Woverloaded-virtual and the fix were really useful; great answers to questions I didn't even know I had. :-) – Jason C May 12 '13 at 07:34