Should Standard Containers Be Subclassed or Inherited?
It is common to come across questions on online forums regarding the practice of subclassing or inheriting standard containers. While this approach may appear convenient for extending container functionality, it raises concerns worth considering.
Why Subclassing Standard Containers is Inadvisable
-
Lack of Virtual Destructors: Standard containers do not possess virtual destructors. This implies that using them polymorphically can lead to potential cleanup issues in derived classes.
-
Violation of Design Principles: Subclassing containers undermines encapsulation and violates the fundamental principle of extending functionality through generically applicable algorithms.
-
Limitations in Extending Behavior: Inheritance should not be the primary method for extending class behavior. This approach binds extended functionality to the interface contract, complicating future modifications.
A More Suitable Approach
Instead of subclassing standard containers, consider:
-
External Algorithms: Implement generic algorithms that operate on containers. This approach promotes flexibility and reduces code duplication.
-
Containment: Utilize containment in a class to enforce specific invariants or add new behaviors independent of the container.
-
Composition: Opt for composition over inheritance whenever feasible. This grants flexibility and allows for the inclusion of a wider range of behaviors in derived classes.
The above is the detailed content of Should You Subclass Standard Containers or Use Composition and Algorithms Instead?. For more information, please follow other related articles on the PHP Chinese website!