Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting and overriding functions of a std::string?

Since std::string is actually a typedef of a templated class, how can I override it? I want to make a UTF-8 std::string that will return the correct length, among other things.

like image 589
jmasterx Avatar asked Nov 17 '10 13:11

jmasterx


3 Answers

If you must define your own string type, then don't inherit from std::string but define your own Character Traits class and do something like

typedef std::basic_string<unsigned char, utf8_traits> utf8string;

See also Herb Sutter's website.

like image 80
Fred Foo Avatar answered Sep 21 '22 07:09

Fred Foo


DON'T DERIVE FROM STRING

std::string, that is, basically the whole basic_string template is not designed to be derived from. There are zillions of articles about that already. It doesn't have any virtual functions so there is nothing to override. The best you can do is hide something. Best is to use composition/aggregation! That is, just keep a member of type string in your class and forward the calls! Again, just to make sure

DON'T DERIVE FROM STRING

like image 31
Armen Tsirunyan Avatar answered Sep 20 '22 07:09

Armen Tsirunyan


It is generally considered a mistake in C++ to derive from a standard library container. However, the functionality you are looking for has already been implemented. Have a look at Glib::ustring.

Hope this helps!

like image 4
Daniel Lidström Avatar answered Sep 23 '22 07:09

Daniel Lidström