Preventing class inheritance, from Bjarne's FAQ (Ziyun English translation)

xiaoxiao2021-03-06  44

Q11: Can I prevent someone from inheriting from my class?

A11: Yes, but why? Ok, maybe there are two reasons:

For efficiency considerations - don't want my function calls being virtual

For security reasons - Make sure my class is not used as a base class (so I don't have to worry about the object when I copy objects).

According to my experience, "efficiency consideration" is often unnecessary. In C , the virtual function call is so fast, and there is not much difference between the normal function call. Please note that virtual mechanism is only enabled by a pointer or a reference call; if you name a target, the C compiler will automatically optimize and remove any additional overhead.

If you say Byebye in order to and "virtual function calls", then it does have the need for "cap" to the class inheritance system. Before the design, I don't have any questions yourself, why are these functions to be designed. I did see such an example: The demanding function of performance is designed, just because "we are used to do so"!

Ok, no matter what, I have so much, after all, you just want to know, for some reasonable reason, can you prevent others from inheriting your class. The answer is ok. Unfortunately, the solution given here is not clean enough. You have to virtual inheritance of a category category that cannot be constructed in your "capped class". Or let the example to tell us everything:

Class usable;

class Usable_lock {friend class Usable; private: Usable_lock () {} Usable_lock (const Usable_lock &) {}}; class Usable: public virtual Usable_lock {// ... public: Usable (); Usable (char *); //. ..}; Usable a; class dd: public usable {}; dd dd; // error: Dd :: DD () Cannot Access // usable_lock :: usable_lock (): Private Member

(See "The Design and Evolution Of C ", 11.4.3)

转载请注明原文地址:https://www.9cbs.com/read-52247.html

New Post(0)