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?
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.
class seal
{
friend class impl1;
friend class impl2;
seal() {} // note it's private!
};
struct interface
{
virtual ~interface() {}
};
struct impl1 : interface, virtual seal
{};
struct impl2 : interface, virtual seal
{};
struct impl3 : impl2{}; // declaration works...
int main()
{
impl1 i1;
impl2 i2;
impl3 i3; // ...but fails to compile here
}
Best I can suggest is making the constructor private and enforcing a factory function for instantiation:
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.