Sobes.tech
Junior — Middle

How can inheritance from a specific class be prevented?

sobes.tech AI

Answer from AI

In C++, preventing inheritance from a specific class can be achieved in several ways:

  1. Use the final keyword (starting from C++11)
class Base final {
    // class body
};

// Attempting to inherit will cause a compilation error
// class Derived : public Base {}; // Error
  1. Make the class constructors private and provide only static methods — this complicates inheritance but does not fully prevent it.

  2. Do not declare virtual methods and do not design the class for inheritance — this is more of a recommendation than a technical restriction.

The simplest and most modern way is to use final for the class, which prohibits inheritance by the compiler.