C++
ABI stability
Learn ABI stability and versioning.
ABI stability
ABI stability means a library's new version keeps working with old compiled code. Binary details like class size, member order and the virtual function table must not change.
ABI break points: adding a new member (size changes), adding a virtual function (vtable changes), reordering members (layout changes), changing an inline function's body (implementation is distributed). Libraries like Qt and libstdc++ use PIMPL and d-pointer techniques to keep ABI stable.
Virtual destructor rule
If a class contains virtual functions, its destructor must also be virtual. This ensures that when a derived class is destroyed through a base pointer, the right destructor runs.
Example: class Base { public: virtual ~Base() = default; virtual int value() const { return 42; } };. Here virtual ~Base() = default asks the compiler to make the default destructor virtual. Following this rule makes ABI less likely to break; derived classes are destroyed safely.
Exercise Write a class with a virtual destructor
Write class Base. In its public section, include virtual ~Base() = default; and virtual int value() const { return 42; }. In main write Base b; std::cout << b.value();.
Show example solution
#include <iostream>
class Base {
public:
virtual ~Base() = default;
virtual int value() const {
return 42;
}
};
int main() {
Base b;
std::cout << b.value();
return 0;
}
Test yourself
-
Complete the PIMPL pointer
class Widget {
struct Impl;
std::unique_ptr<Impl> ____;
};
Show answer
class Widget {
struct Impl;
std::unique_ptr<Impl> pimpl;
};
-
Match each technique to its role
- PIMPL
- Hidden implementation
- virtual destructor
- Derived class destruction
- #pragma pack
- Struct alignment
- extern C
- Unmangled symbol
-
Which change breaks the ABI?
class Base { public: virtual ~Base(); int x; };
- Adding a private member
- Adding a comment
- Adding a new virtual function
- Changing a function's body without renaming
Show answer
Adding a new virtual function — A new virtual function changes the vtable; old code calls the wrong function.
Next lesson: Summary - ABI