I want to extend std::string, but not for the reason you might think

c++, explicit, typedef

Solution

The usual rule still applies: the class isn't designed to be inherited from, and its destructor isn't virtual, so if you ever upcast to the std::string base class, and let the object be destroyed, your derived class' destructor won't be called.

If you can guarantee that this will never happen, go ahead.

Otherwise, you could make the `std::string` a member of your class, rather than a base class. or you could use private inheritance. The problem with this approach is that you'd have to re-implement the string interface for the class to be usable as a string.

Or you could just define your class to expose a `getString()` function which returns the internal `std::string` object. Then you can still pass your own class around, and the compiler will complain if you try to pass a `std::string`, but the internal string is accessible when you need it. That might be the best compromise.

Problem

I have a method that effectively takes a string. However, there is a very limited subset of strings I want to use. I was thinking of typedef'ing std::string as some class, and call the functions explicit. I'm not sure that would work, however. Ideas?

Original source