Home >Backend Development >C++ >Is Inheriting from C STL Containers Risky?
Risks of Inheriting from C STL Containers
The question posed is whether there are any real risks associated with inheriting from standard C containers. The author argues that using a typedef, such as typedef std::vector
Use Case
Consider the following code snippet:
The author suggests that an arbitrarily hapless user could introduce an error in the ??? section that would cause a problem with Charges (the derived class), but not with Rates (the typedef).
Virtual Destructors
The key issue here is that standard C containers do not have virtual destructors. Consequently, you cannot handle them polymorphically. If you and all users of your code adhere to this principle, it is not inherently wrong to inherit from standard containers. However, the author recommends composition for clarity.
Composition over Inheritance
Instead of inheriting from a container, it is cleaner and safer to use composition. This involves creating a new class that contains an instance of the container as a member variable. This allows for more flexibility and control over the functionality of your class.
In this use case, for example, defining a new Rates class that contains an instance of std::vector
The above is the detailed content of Is Inheriting from C STL Containers Risky?. For more information, please follow other related articles on the PHP Chinese website!