Search code examples
c++virtual-functions

Why I have to redeclare a virtual function while overriding [C++]


#include <iostream>
using namespace std;

class Duck {
public:
        virtual void quack() = 0;
};

class BigDuck : public Duck {
public:
  //  void quack();   (uncommenting will make it compile)

};

void BigDuck::quack(){ cout << "BigDuckDuck::Quack\n"; }

int main() {
        BigDuck b;
        Duck *d = &b;
        d->quack();

}

The code above doesn't compile. However, when I declare the virtual function in the subclass, then it compiles fine.

If the compiler already has the signature of the function that the subclass will override, then why is a redeclaration required?

Any insights?


Solution

  • The redeclaration is needed because:

    • The standard says so.
    • It makes the compiler's work easier by not climbing up the hierarchy to check if such function exists.
    • You might want to declare it lower in the hierarchy.
    • In order to instantiate the class the compiler must know that this object is concrete.