CodeBlanks Logo Icon CodeBlanks

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.

Practice 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();.

Starter code

main.cpp
#include <iostream>

// Define the Base class here

int main() {
    // Create a Base instance and print value
    return 0;
}

Sample solution

main.cpp
#include <iostream>

class Base {
public:
    virtual ~Base() = default;
    virtual int value() const {
        return 42;
    }
};

int main() {
    Base b;
    std::cout << b.value();
    return 0;
}

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the PIMPL pointer

Question
class Widget {
    struct Impl;
    std::unique_ptr<Impl> ____;
};
Answer
class Widget {
    struct Impl;
    std::unique_ptr<Impl> pimpl;
};

Explanation: The pimpl pointer hides the Impl definition.

2 Match each technique to its role

Term Meaning
PIMPL Hidden implementation
virtual destructor Derived class destruction
#pragma pack Struct alignment
extern C Unmangled symbol

3 Which change breaks the ABI?

main.cpp
class Base { public: virtual ~Base(); int x; };
  • Adding a private member
  • Adding a comment
  • Adding a new virtual function Correct answer
  • Changing a function's body without renaming

Explanation: A new virtual function changes the vtable; old code calls the wrong function.

All lessons in Expert