Consider following example
#include <iostream>
struct PureVirtual {
virtual void Function() = 0;
};
struct FunctionImpl {
virtual void Function() {
std::cout << "FunctionImpl::Function()" << std::endl;
}
};
struct NonPureVirtual : public FunctionImpl, public PureVirtual {
using FunctionImpl::Function;
};
int main() {
NonPureVirtual c;
c.Function();
}
Compiler (GCC 4.9, Clang 3.5) exits with error
test.cpp:18:20: error: variable type 'NonPureVirtual' is an abstract class
NonPureVirtual c;
^
test.cpp:4:18: note: unimplemented pure virtual method 'Function' in 'NonPureVirtual'
virtual void Function() = 0;
^
But when I don't derive form PureVirtual
everything is OK. This is weird because Standard 10.4.4 says
A class is abstract if it contains or inherits at least one pure virtual function for which the final overrider is pure virtual.
They are not saying anything about what the final overrider is but I suppose it should be FunctionImpl::Function()
especially when I made it available through using
directive. So why is still NonPureVirtual
abstract class and how can I fix this.
A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be “pure” using the curious =0 syntax. For example: class Base {
This was a rather long-winded way of calling out a weird corner case in C++ that most people don't even realize exists: A pure virtual function can have an implementation.
A pure virtual function makes it so the base class can not be instantiated, and the derived classes are forced to define these functions before they can be instantiated. This helps ensure the derived classes do not forget to redefine functions that the base class was expecting them to.
A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly.
FunctionImpl::Function
and PureVirtual::Function
are different functions from different classes.
Their respective types are void (FunctionImpl::*)()
and void (PureVirtual::*)()
.
Since PureVirtual
and FunctionImpl
are unrelated classes, these function types are unrelated.
They happen to have the same name and the same parameters and return type, but since they're different, the using FunctionImpl::Function
line doesn't make that function an override of the one in PureVirtual
.
And if you declared a variable of type void (PureVirtual::*)()
, you wouldn't be able to assign FunctionImpl::Function
to it.
In other words, the final override of PureVirtual::Function
is the original one in PureVirtual
, which is pure virtual.
For making what you want possible, Matthieu M.'s answer (using a forwarding call) is the way to go, it seems.
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