1
class MyString :public string {
public:
    using string :: string;
    using string :: operator=;
    bool operator== (MyString&);
    bool operator<  (MyString&);
    bool operator>  (MyString&);
    MyString& operator=  (MyString&);
    MyString& operator=  (string&);
    MyString operator() (int, int);
    friend ostream & operator<<(ostream&, MyString&);
};

MyString MyString::operator() (int a, int b) {
    MyString os;
    os = string::substr(a, b);
    return os;
}

Note: I'm using cstring

It's my learning experiment. I am confused when it comes to very simple derivation like code above.

  1. Suppose I just want to add feature that can get substring by (int, int) operator, but I realize I can't use those functions that take MyString parameters.

  2. I have tried to use using for those operators ==, <, > but that doesn't work. The compiler tells me that string don't have those operator, I wonder it's because those functions in string are not virtual?

  3. Is the code in operator() legal base on my functionality set in public:? The compiler doesn't tell me any thing. But I'm quite skeptical.

PeterLai
  • 105
  • 1
  • 9

1 Answers1

1

Do not derive from std::string. Some reasons are explained here, so I won't repeat them.

If you want to extend functionality of std::string, you can either

Make a wrapper class

class MyString
{
    std::string underlying_string;
public:
    /* methods */
}

Problem is, that it has nothing to do with std::string anymore. It can't be assigned to std::string, nor passed to function accepting std::string1. Also it is quite a bit verbose - consider adding all overloads of operator+ (std::string + MyString, MyString + std::string, maybe also MyString + char*, add consts and move semantics) and you are at ~16 methods?

Another option, is to define just helper method.

std::string do_super_cool_thing(const std::string& str, int a, int b)
{
    return magic(str, a, b);
}

  1. Can be helped with non-explicit ctor MyString::MyString(std::string), user defined conversion operator std::string(), but it has different meaning than inheritance.
Community
  • 1
  • 1
Zereges
  • 5,139
  • 1
  • 25
  • 49
  • If you want to pass it to a function accepting std::string, you can define `operator std::string()` on the class. [user-defined conversions](http://en.cppreference.com/w/cpp/language/cast_operator) can be incredibly useful. – Taywee Jun 26 '16 at 21:22