C++11 introduced the final specifier, which allows a base class to prevent derivation or overriding of virtual functions in derived classes.
How can I enforce similar constraints on class inheritance and function overriding pre C++11?
On
Best I can suggest is making the constructor private and enforcing a factory function for instantiation:
class Foo
{
public:
static Foo* makeInstance(int initialX)
{
return new Foo(initialX);
}
private:
Foo(int initialX) :x(initialX) {}
int x;
int setX(int value) { x = value; }
int getX() { return x; }
};
That should prevent inheritance. But it does require your callers to explicitly instantiate the object via the static makeInstance function or similar. And then explicitly delete it.
You can also have it return the object copy instead of by pointer.
static Foo makeInstance(int initialX)
{
return Foo(initialX);
}
Making the class behave somewhat like "final" can be achieved using virtual inheritance and class friendship.
Personally I would not recommend using it in this manner, but it's certainly possible.
https://godbolt.org/z/MjKhbaTo8