devxlogo

Inhibit Derivation from a C++ Class

Inhibit Derivation from a C++ Class

If no other classes can derive from a class, then you know that all the pointers to that class point to objects of a uniform size. This can simplify memory management and file storage. The idea is to first define a dummy class with a private default constructor. Then virtually derive all the other classes for which you want to inhibit derivation from the dummy class and declare them as friends of the dummy class:

 class CDummy{private:  //Private default constructor  CDummy() {}  friend class CX1;  friend class CX2;  //...};

The class CDummy is a virtual base for the classes CX1, CX2.

 class CX1 : virtual public CDummy{public:  //Constructor, can invoke CDummy's private constructor.  CX1() {}};

The constructor of CDummy is private, but CX1 is a friend, so it can invoke that private constructor. But here’s what happens if you try to derive a class CY1 from CX1:

 class CY1 : public CX1{public:  //Constructor, cannot invoke CDummy's private constructor  CY1() {}};

Because CY1 has CDummy as a virtual base, it must initialize it, but it cannot. You get a compile time error, for example in the case of the VC++ compiler you get the message:

 "'CDummy::CDummy' : cannot access private member declared in class'CDummy'"
See also  Why ChatGPT Is So Important Today
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