2

I have the following struct:

struct A {
  std::string data;
  bool flag;
};

I want users of my class to be able to use it like a string in most cases. This means the == operator, iterators, [] indexing, etc. I'd have to write a bunch delegating methods for that. But instead I could do this:

struct A : std::string {
  using std::string::string; // Bring in all constructors.
  bool flag;
};

Does this have any downsides?

pieter3d
  • 135
  • 6
  • Do you use dynamic polymorphism? If yes, I am not sure that std::string have a virtual destructor :/ – Martin Morterol Oct 08 '19 at 06:02
  • What's the purpose of the flag? Is it used to indicate whether the underlying string is valid or not? According to https://stackoverflow.com/a/1647316/12160191 STL containers are not designed to be inherited from. – Empty Space Oct 08 '19 at 06:06
  • The flag is metadata (i.e. some information about the contents of the string). I suppose composition is the better way to go here. – pieter3d Oct 08 '19 at 06:13

0 Answers0