Josh Bartholf
Josh Bartholf

Reputation: 5

How is the string type created in c++?

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

Answers (3)

ChanDon
ChanDon

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

Rick Yorgason
Rick Yorgason

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:

  • The length of the string is usually included as a member variable, so you don't have to keep calling strlen to find the length.
  • The std::string class uses templates, so you're not limited to the char type. If you're using Unicode, you can use std::wstring, which uses 16- or 32- bit strings by replacing the char type with the wchar_t type.
  • Usually there's lots of optimizations to choose from. Lately the most popular has been the "short string" optimization.

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

Dave
Dave

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

Related Questions