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)
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]
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With