Re: Deriving a class from string
Sam <sam@email-scan.com> wrote:
Paulo da Silva writes:
I need a class with several string methods. I don't want to use the
string class itself because in future I may want to redefine it to
use other ways to implement the same (needed) methods but with a
different behaviour.
[snip]
What is the minimum code to have all string methods available in
myClass?
class myClass : public std::string {
};
Feel free to use myClass::substr(), myClass::begin(), myClass::end(), etc???
as expected.
Sam's idea of publicly deriving your class from std::string seems the
obvious answer, but I recommend against it. The std::string class was
not designed to be derived from and doing so could cause all kinds of
problems, some of which are hard to track down (e.g., object slicing.)
I suggest you use private inheritance instead of public. Implement the
constructors you need and export the minimum number of string functions
you need with using declarations.
class MyClass : private std::string
{
public:
MyClass() { }
explicit MyClass(const char* s): std::string(s) { }
// and so on, only for the constructors you need
// conversion operators made explicit to guard against
// accidental object slicing and passing.
explicit MyClass(std::string s): std::string(s) { }
std::string std_string() const { return *this; }
using std::string::operator[];
using std::string::size;
// and so on, only for the functions you actually need.
};
Then in the future, when you want to change the behavior of one of the
functions you exported, all you need to do is replace the using
declaration with your own code.