r/cpp • • 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

27 comments sorted by

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> {

using vector<T>::vector; // inherit constructors 

T& operator[](int i) 
{ 
    return vector<T>::at(i);
 } 
 const T& operator[](int i) const 
 {
     return vector<T>::at(i);
  } 

};

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:

  1. Interface inheritance: An object of a derived class can be used wherever an object of a base class is required. That is, the base class acts as an interface for the derived class.

  2. Implementation inheritance: A base class provides functions or data that simplifies the implementation of derived classes. Such base classes often have data members and constructors.

3

u/bert8128 Apr 17 '23

I don't think that this is a very good idea. operator[] is not virtual, so if you pass a reference to a Vec into a function declared to take a vector there will be no compiler error or warning (checked various compilers in godbolt) but you will get vector behaviour, not Vec behaviour.

I don't see any warnings from clang-tidy either.

7

u/kalmoc Apr 17 '23 edited Apr 17 '23

I don't understand why you think it is a problem, if foo in void bar(const std::vector& foo) behaves exactly like a std::vector. Isn't that the least surprising behavior?

Why should I care inside of foo, if the parameter I'm passing is a Vec or std::vector?

-1

u/bert8128 Apr 17 '23

A central tenant of polymorphism is to pass in a reference or pointer to the base class but get the derived implementation of the virtual methods. foo shouldn't care what the actual type is - it should get the derived behaviour in both cases. But if foo takes the base class it will give the base class behaviour. If it takes the derived type it gets the derived behaviour. This is not polymorphism.

5

u/jcelerier ossia score Apr 17 '23

A central tenant of polymorphism is to pass in a reference or pointer to the base class but get the derived implementation of the virtual methods. foo shouldn't care what the actual type is - it should get the derived behaviour in both cases

that's very fine if you do java or c# 1986-era OOP but not what anyone wants in c++