Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Derive class off of std::string class to add extra function?

Tags:

c++

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)

like image 363
Jay Avatar asked Dec 24 '22 19:12

Jay


1 Answers

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

like image 90
Mike Seymour Avatar answered Jan 27 '23 13:01

Mike Seymour