Why Should One Refrain from Deriving from std::string
In his book Effective C , Scott Meyers advises against deriving from the std::string class, primarily due to its lack of a virtual destructor. However, this is not the only reason to avoid such inheritance.
Defining Criteria for Inheritance
To serve as an appropriate base class, a class must:
std::string as a Base Class
std::string fails to meet these criteria for the following reasons:
Additionally, even in scenarios where inheritance is solely for reusability, C lacks mechanisms to prevent clients from creating objects of a derived class using a base class pointer. This can violate the intended purpose of restricting such usage.
Consequences of Inheritance Violation
Ignoring these guidelines can result in code that is:
In conclusion, inheritance in C should be reserved for polymorphic situations, and std::string should not be used as a base class due to its design constraints and the slicing problem. Employing alternative methods like non-member functions or composition promotes idiomatic C practices and ensures code clarity and reliability.
The above is the detailed content of Why Should You Never Inherit from std::string in C ?. For more information, please follow other related articles on the PHP Chinese website!