"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > When is It Acceptable to Inherit from C++ Standard Library Classes?

When is It Acceptable to Inherit from C++ Standard Library Classes?

Published on 2024-11-08
Browse:300

When is It Acceptable to Inherit from C   Standard Library Classes?

Extending the C Standard Library through Inheritance

While it's often assumed that inheriting from C Standard Library classes is not desirable, there are notable exceptions.

Identifiable Classes for Inheritance

Determining whether a Standard Library class is intended for inheritance can be challenging. However, the following guidelines can provide some insight:

  • If the class has virtual methods, it's a possible candidate for inheritance.
  • Excessive "friend" declarations indicate encapsulation issues, making inheritance less suitable.
  • Templates should be considered for specialization instead of inheritance.
  • Policy-based mechanisms, like std::char_traits, suggest inheritance is not intended.

Derived Class Requirements

When inheriting from Standard Library classes, the Liskov Substitution Principle (LSP) should be applied. Observable behavior, such as the what() function in std::exception, should match the base class. Conformance to the Standard is less of a concern than correctness in this context.

Conclusion

While the Standard itself lacks explicit guidance on extending the Standard Library, it's crucial to carefully consider the intended usage of classes and apply principles of inheritance judiciously.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3