Should a virtual function essentially have a definition?

c++, undefined-reference, virtual-functions

Solution

The ISO C++ Standard specifies that all virtual methods of a class that are not pure-virtual must be defined.

Reference:

C++03 Standard: 10.3 Virtual functions [class.virtual]

A virtual function declared in a class shall be defined, or declared pure (10.4) in that class, or both; but no diagnostic is required (3.2).

So either you should make the function pure virtual or provide a definition for it.

If you are using gcc, You might get some weird errors if you fail to follow this standard specification. The gcc faq doccuments it as well:

The ISO C++ Standard specifies that all virtual methods of a class that are not pure-virtual must be defined, but does not require any diagnostic for violations of this rule `[class.virtual]/8`. Based on this assumption, GCC will only emit the implicitly defined constructors, the assignment operator, the destructor and the virtual table of a class in the translation unit that defines its first such non-inline method.

Therefore, if you fail to define this particular method, the linker may complain about the lack of definitions for apparently unrelated symbols. Unfortunately, in order to improve this error message, it might be necessary to change the linker, and this can't always be done.

The solution is to ensure that all virtual methods that are not pure are defined. Note that a destructor must be defined even if it is declared pure-virtual `[class.dtor]/7`.

Problem

Is it essential to have a definition for a virtual function? Consider this sample program below: ``` #include <iostream> using namespace std; class base { public: void virtual virtualfunc(); }; class derived : public base { public: void virtualfunc() { cout << "vf in derived class\n"; } }; int main() { derived d; return 0; } ``` This gives the link-error: In function `base::base()`:: undefined reference to `vtable for base` I do not have the definition for the virtual function in base class. Why is this error occurring even though I have not explicitly invoked the virtual function? The interesting thing which I find is that if I do not instantiate an object of class `derived`, the link error is no longer there. Why is this? What has instantiation got to do with the above link error?

Original source