Search code examples
c++inheritanceinterfaceabstract-classpure-virtual

Declaring an "interface" in C++ and not emmiting its vtable to every translation unit


According to this answer, the way to declare a class in C++ conceptually analogous to an interface is like this:

class IDemo
{
public:
    virtual ~IDemo() {}
    virtual void OverrideMe() = 0;
};

But when I do this, I get the warning: 'IDemo' has no out-of-line virtual method definitions; its vtable will be emitted in every translation unit. Is there a proper way to use such interfaces in a project without polluting every translation unit with those vtables?


Solution

  • You already have a non-pure virtual function: the destructor! Just define it in its own translation unit.

    // IDemo.h
    
    class IDemo
    {
    public:
        virtual ~IDemo();
        virtual void OverrideMe() = 0;
    };
    

    // IDemo.cpp
    
    IDemo::~IDemo() = default;