# C++: undefined reference to `vtable for X' — virtual function not defined

**Code:** `undefined reference to vtable` · **Category:** C/C++ · **Seen on:** C/C++, GCC, Clang

The linker cannot find the class's virtual table, which means at least one virtual member function was declared but never defined (or the file defining it isn't linked).

## Meaning

The compiler emits the vtable in the file that defines the class's first non-inline virtual function (the "key function"). If that function has no body, or its .cpp is missing from the build, you get `undefined reference to vtable for X` and often `typeinfo for X` too.

## Common causes

- Virtual function declared but never defined
- The .cpp containing the key function is not part of the target
- Pure virtual function called through a base that has no definition
- Missing virtual destructor body (`virtual ~X();` never defined)

## Quick fix

1. Define every non-pure virtual function (or `= default`)
2. Add the missing .cpp to the build
3. Define the destructor: `virtual ~X() = default;`

## Detailed fix by platform

### C++

1. Write `virtual ~Base() = default;` in the header
2. Check that every override has a body or `= 0`

### CMake

1. Re-run CMake after adding files; globbed sources are not detected automatically: `cmake -S . -B build`

## Code examples

### Key function missing

```cpp
// widget.h
struct Widget {
    virtual void draw();               // declared ...
    virtual ~Widget() = default;
};

// widget.cpp
#include "widget.h"
void Widget::draw() {}                 // ... and defined here, so the vtable exists
```

## How to diagnose

1. **Class** — Which class is in the message?
2. **Definitions** — Does each virtual function have a body?
3. **Build** — Is its .cpp compiled and linked?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/vtable-undefined-reference)
