devxlogo

Preventing Derivation

Preventing Derivation

In general, disabling inheritance is a dubious idea. Yet under some circumstances it may be useful. To do this, declare the class in question (called A in our example) as a friend of another class (called Lock in our example). Locks constructor must be private:

 class A;class Lock { friend class A;private: Lock() {} };

Next, virtually derive the class in question from Lock:

 class A : virtual public Lock {  // ...public: A(); A(int);//.. additional ctors, dtors etc.};

Consequently, any attempt to derive from A will fail:

 A a; // OKclass Derived : public A { };Derived d;// error: Deriveds ctor cant access Locks ctor
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist