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)

1 Answer 1

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].)

Sign up to request clarification or add additional context in comments.

8 Comments

Also regarding deriving from standard library classes in general, here are some things to consider.
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.
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?
@CássioRenan: I'll leave such things to comments, if necessary. No beginner should be using obsolete dialects.
@rozina: This isn't really the place for a language tutorial. See en.cppreference.com/w/cpp/language/…, or your favourite C++ book. To answer your questions: yes and yes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.