Reputation: 5
How was the "string" type created in C++? In C, strings are character arrays, but how did C++ turn the character arrays into the "strings" we know of in C++?
Upvotes: 0
Views: 181
Reputation: 401
It's just a class named 'string', something like this:
class string
{
private:
//members
char* c;
public:
//methods
bool operator==(const string& other) const;
};
Upvotes: 0
Reputation: 1666
The character array is still in there, it just has a class wrapped around it. Imagine something like this:
class String
{
private:
char* stringData;
public:
String(const char* str)
{
stringData = new char[strlen(str)+1];
strcpy(stringData, str);
}
~String() { delete[] stringData; }
String& operator += (const String& rhs)
{
char* newStringData = new char[strlen(rhs) + strlen(stringData) + 1];
strcpy(newStringData, stringData);
strcpy(newStringData + strlen(stringData), rhs);
delete[] stringData;
stringData = newStringData;
return *this;
}
};
That's obviously a very incomplete example, but you get the idea, right?
The actual implementation of std::string is pretty comprehensive, but it's nothing you couldn't do yourself. Here's some differences in the official std::string class from what I posted:
Once you've relatively comfortable with C++, you should try writing your own string class. It's not something you would use in practice, but it's a really good exercise for library writing.
Upvotes: 9
Reputation: 11162
By writing a class that encapsulated a lot of string functions, and by overloading a bunch of operators.
string really is just a class like any other:
string s = "hello"
is an overload of the equals operator defined:
string& operator= ( const char* s );
for example.
Upvotes: 3