#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?
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.
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.
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.
No, the virtual keyword on derived classes' virtual function overrides is not required.
The redeclaration is needed because:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With