Home  >  Article  >  Backend Development  >  When is It Acceptable to Inherit from C Standard Library Classes?

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

Susan Sarandon
Susan SarandonOriginal
2024-11-03 13:28:03512browse

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.

The above is the detailed content of When is It Acceptable to Inherit from C Standard Library Classes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn