Home > Backend Development > C++ > Is Inheriting from C STL Containers Risky?

Is Inheriting from C STL Containers Risky?

Barbara Streisand
Release: 2024-11-29 03:45:09
Original
855 people have browsed it

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 Rates;, is a safer approach. However, they propose a specific use case to explore any potential hazards.

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 would allow you to add additional functionality while still leveraging the underlying container. This approach also ensures that the destructor of your new class is properly handled, regardless of the base container implementation.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template