Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 219
sud03r Avatar asked Jun 02 '10 13:06

sud03r


People also ask

Do I need to override virtual functions?

It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used. A class may have virtual destructor but it cannot have a virtual constructor.

What happens if virtual function is not overridden?

In addition, if you do not override a virtual member function in a derived class, a call to that function uses the function implementation defined in the base class. A function that has a deleted definition cannot override a function that does not have a deleted definition.

Can override be done without virtual keyword?

You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.

Is there any reason to mark a function virtual If you are not going to have a derived class?

No, the virtual keyword on derived classes' virtual function overrides is not required.


1 Answers

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.
like image 85
the_drow Avatar answered Sep 25 '22 09:09

the_drow