Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't g++ complain when derived class calls pure virtual function of base?

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;
}
like image 957
Agnel Kurian Avatar asked Sep 27 '12 17:09

Agnel Kurian


2 Answers

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.

like image 54
Mike Seymour Avatar answered Sep 22 '22 14:09

Mike Seymour


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.

like image 39
Pete Becker Avatar answered Sep 20 '22 14:09

Pete Becker