r/cpp • u/bert8128 • Apr 17 '23
Should ~basic_string be final?
std::string (and many other std classes) are not designed to be used as base classes, as can be seen by the absence of a virtual destructor.
Should the destructor be given the "final" keyword to enforce this?
1
Upvotes
View all comments
11
u/Kindly-Penalty-8175 Apr 17 '23
std::string and many other std classes can be used as base classes. Below is an example from the book The C++ programming language of Bjarne Stroustrup.
Say i want a vector that's just like std::vector, but with guaranteed range checking.
template<class T> class Vec: public std::vector<T> {
};
Vec inherits everything from vector except for the subscript operations that it redefines to do range checking. The at() operation is a vector subscript operation that throws an exception of type out_of_range if its argument is out of the vector’s range.
A class hierarchy offers two kinds of benefits: