Dangers of Inheriting from std::string
While using inheritance can provide code reusability, it's important to understand the specific requirements for classes to act as base classes. One crucial consideration highlighted by Effective C is that a class should have a virtual destructor if it intends to behave polymorphically.
However, std::string does not possess a virtual destructor, which raises concerns about inheriting from it. The question arises whether the absence of a virtual destructor is the sole reason for avoiding inheritance from std::string.
In C , inheritance is primarily used for two purposes:
Non-polymorphic inheritances have no practical value in C and can be avoided. Free functions provide a more suitable alternative, allowing you to extend classes without forcing clients to switch to your custom string class.
The Slicing Problem
In C , classes are value types, unlike reference types in other OO languages. This leads to the slicing problem, where passed-by-value objects are truncated to the base class size, leading to inconsistencies. This is demonstrated in the code snippet below:
int StringToNumber(std::string copyMeByValue) { // ... Your code to convert 'copyMeByValue' to a number. }
If you pass a derived object of std::string to this function, the slicing problem will occur, resulting in unexpected behavior. Since non-derived functions are tightly coupled with base class members, these inconsistencies can arise.
Conclusion
Avoid inheriting from std::string unless you explicitly need polymorphic behavior. For code reusability purposes, prefer non-member functions and members in classes that are not intended for inheritance. By adhering to this practice, you can ensure code maintainability and prevent potential issues associated with inheritance mismatches.
The above is the detailed content of Why Should I Avoid Inheriting from `std::string` in C ?. For more information, please follow other related articles on the PHP Chinese website!