But, how to make it final, yet allow one class to inherit from it?
That's not possible.
We mostly need to derive a mock class from real class (with or without late-binding, hence virtual isn't important).
If the class is final, you do not need to derive from it. If you do need to derive from it, it is not final. Pick one.
Edit: You can add restrictions to your class, but those come at their own cost to the interface:
class Generator // not final
{
Generator(); // the only accessible constructor is private
// whitelist who has access to this constructor
friend class MockGenerator;
public:
// no public constructors here except for copy & move
Generator(Generator&);
Generator(Generator&&);
...
// provide controlled access to the private constructor
static Generator make_generator() { return Generator(); }
// rest of API here
};
This is a class that allows it's factory and MockGenerator specializations to call it's constructor. This comes at the price of blocking trivial construction though.
Old code (no longer compilable):
Generator instance;
New code (enforced by the private constructor):
auto instance = Generator::make_generator();