5

First of all, I know that the std::string class has all the functions I could possibly need. This is just for testing purposes to see what I'd be able to do in the future.

Anyway, say I had this:

class MyString : public std::string { }

How would I then, for example, use:

MyString varName = "whatever";

because surely I'd get an error because "whatever" is a std::string not a member of the MyString class?

If you understand what I mean, how would I fix this?

(and by the way, I know this is probably a really silly question, but I am curious)

Jay
  • 81
  • 1
  • 7

1 Answers1

11

Deriving from a class simply to add member functions isn't a great idea; especially a non-polymorphic class like std::string. Instead, write non-member functions to do whatever you want with the existing string class.

If you really want to do this nonetheless, you can inherit the constructors:

class MyString : public std::string {
public:
    using std::string::string;
};

Now you can initialise your class in any way that you can initialise std::string, including conversion from a character array as in your example. (By the way, "whatever" isn't a std::string, it's a zero-terminated character array, const char[9].)

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 2
    Also regarding deriving from standard library classes in general, [here are some things to consider](https://stackoverflow.com/questions/1073958/extending-the-c-standard-library-by-inheritance). – Cory Kramer May 04 '15 at 11:54
  • Maybe you should add a note that this only works in C++11. It's been a while since it was released, I know, but a beginner using gcc without `-std=c++11` will still get a compiler error and be confused. – Not a real meerkat May 04 '15 at 11:57
  • How does that work exactly. You can now write `MyString str("hello")` I assume. Can you also add new constructor overloads to the ones from std::string? – rozina May 04 '15 at 12:04
  • 4
    @CássioRenan: I'll leave such things to comments, if necessary. No beginner should be using obsolete dialects. – Mike Seymour May 04 '15 at 12:04
  • 2
    @rozina: This isn't really the place for a language tutorial. See http://en.cppreference.com/w/cpp/language/using_declaration#Inheriting_constructors, or your favourite C++ book. To answer your questions: yes and yes. – Mike Seymour May 04 '15 at 12:11
  • Thank you. Didn't know about this feature of the language. I am still working with C++03.. :) – rozina May 04 '15 at 12:13
  • @MikeSeymour I completely agree, but yet, they still do it. I see your point, though: A comment should work fine for this purpose (And make it clear that C++ is not C++03 anymore). – Not a real meerkat May 04 '15 at 12:34
  • Good answer and thanks to everyone in the comments as well. And yes, I was already using C++11 (not sure why it hasn't been selected as default in IDEs like Code::Blocks tbh). Thanks everyone :) – Jay May 04 '15 at 15:34