Reputation: 59466
I have a class Base
with a pure virtual function f()
. Another class Derived
derives from Base
. I call f()
from within Derived
. And using g++, I get an error from the linker.
[agnel@dooku tmp]$ g++ pure_virtual_function_call.cpp
/tmp/ccGQLHi4.o: In function `Derived::f()':
pure_virtual_function_call.cpp:(.text._ZN7Derived1fEv[_ZN7Derived1fEv]+0x14): undefined reference to `VirtualBase::f()'
collect2: error: ld returned 1 exit status
It seems to me that the error was caught by the linker. Why didn't the compiler report this error? Why leave it to the linker?
Here is the code:
#include <iostream>
using namespace std;
class VirtualBase {
public:
virtual void f() = 0;
};
class Derived : public VirtualBase {
public:
void f(){
VirtualBase::f();
cout << "Derived\n" ;
}
};
int main(){
Derived d;
d.f();
return 0;
}
Upvotes: 5
Views: 654
Reputation: 254481
Because pure virtual functions can have definitions and, if they do, you are allowed to call them non-virtually using the syntax VirtualBase::f()
.
The compiler has no way to tell whether you intend the function to be defined or not, and so the error can only be detected by the linker.
Upvotes: 12
Reputation: 76315
It's not an error to call a pure virtual function. It's an error to call any function that does not have a definition. A pure virtual function can have a definition.
Upvotes: 8