Devansh Mohan Kaushik Devansh Mohan Kaushik - 1 year ago 41
C++ Question

if vtable is created at compile time , why this error is an linker error and not compile error?

The following piece of code give me the error

undefined reference to `vtable for Derived'

Code :

#include <iostream>
class base{
virtual ~base(){}
virtual void test()
class Derived:public base{
void test();
int main() {
base* b = new Derived ();
delete b;

which i understand is because the virtual fucntion
is declared but not defined in
class Derived

But when i compile with
g++ -c file.cpp
which as per this Compile or assemble the source files, but do not link. It does not give me any errors and compiles fine. Hence the above error is generated at linking time and not compile time.
From what i learned wasn't the
created at compile time. Then why do i not get the error at compile time itself?

Answer Source

However you formed the view that a vtable must be created at compile time, you are mistaken.

Separate compilation is a core concept in the standard. It is the reason that a compilation unit (aka source file) can compile, given any declaration of a function it needs - even if it doesn't have visibility of the definition.

In the typical "compile then link" build chain, this allows a compilation unit (source file) to compile, given any declaration of a function (member function or not) that might be defined in another compilation unit.

The absence of the definition of a function then needs to be detected by the linker.

Practically, this means that the compiler may emit information about the vtable, but it will be the linker that (ahem) links the specification of the vtable to the actual member functions.