I have a question regarding the declaration of pure virtual functions in C++. I come from a Java background, and so I see pure virtual functions as a way to define abstract classes and the idea of interfaces. My question is simple, when we define a pure virtual function in C++ we have to write something like this:
virtual void function() =0
The void could be of any type, but we have to include the equals to 0 and the virtual keyword. I understand the "equals to 0" part as being used to define a pure function, but my question is why does it have to be virtual? Couldn't we just define it without the virtual keyword? Is this just a part of C++ that is included in the definition of pure virtual functions or is there a logical reason as to why "abstract methods" must be virtual as well?
A non-virtual pure function doesn't make much sense. Fundamentally, a function is a named section of code that can be called in some way. If you make it pure, that means there is (possibly) no section of code at all; there is only the name.
This does make sense for
virtualmember functions because the implementation could be provided by one of the derived classes. Even ifBase::foo()doesn't exist, it's possible that callingBase::foo()will callDerived::foo()through dynamic dispatch. However, withoutvirtual, no such mechanism exists.Similarly,
abstract finalmethods don't make much sense in Java. A non-virtual member function in C++ can be consideredfinalsince there is no mechanism for overriding it.