I have the following declaration in my String.h file:
private:
char* nstring;
int nlength;
};
The following are three constructors I've implemented in String.cpp. I would like these to be reviewed.
// Default constructor for this class. Initializes an empty string.
string::string() {
nlength = 1; // for "\0" terminating character at the end of the char array
nstring = new char[nlength];
nstring[nlength - 1] = '\0';
}
// Constructor for String class. Initializes a string based on the given C string.
string::string(const char* input) {
nlength = strlen(input) + 1;
nstring = new char[nlength];
for (int i = 0; i < (nlength - 1); i++) {
nstring[i] = input[i];
}
nstring[(nlength - 1)] = '\0';
}
// Copy constructor for String class.
// Initializes a string from an already existing string.
// The contents of the existing string should be copied over to this string.
string::string(const string& S) {
nlength = S.nlength;
nstring = new char[nlength];
for (int i = 0; i < (nlength - 1); i++) {
nstring[i] = S.nstring[i];
}
nstring[(nlength - 1)] = '\0';
}