Your string class is to work with any string given to it by the user.
For example, I should be able to do:
1 2 3
|
String s; // string is zero-length
String hw( "Hello World!" ); // string has length 13 including the \0
String longStr( "fhalkfhsdakfhaklfhaslfajfhalfhdsafsafas" ); // etc, etc.
| |
Your string class has to be able to work with any of those. Having said that, how does your string class know at compile time the length of the string being given to it? Answer: it doesn't. At runtime you have to allocate enough memory to hold the string being given to it.
That's what Length is for.
Capacity works as follows: it is typical for STL containers (such as vector<>, deque<>, and string) to allocate space for more elements/characters than is needed. Why? So that when the user adds elements to the vector/deque in a loop, the data structure does not have to be resized one larger each time through. Same for strings. Capacity therefore is a measure of the number of elements/bytes actually allocated.
So for example,
String hw( "Hello World!" );
has Length = 13, but the String class might allocate 20 bytes instead, and just not use the last 7. then when the programmer does:
hw += "Hi!";
the string already has enough Capacity to store the additional 3 characters without having to reallocate a larger Mem block.