I've my GString class that accepts a c style string as parameter:
1 2 3 4 5 6 7 8
class GString
{
private:
char* mainString;
int size;
public:
int Size() const { return size; } // returns the size EXCLUDING the \0 NULL character
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// CONSTRUCTOR
GString(constchar* CstyleString)
{
// +1 for the NULL character at the end (/0)
size = strlen(CstyleString);
mainString = newchar[size+1];
int i = 0;
// -1 because we want to set the NULL character AFTER the copy of the character from one vector to another
for (i = 0; i < size; i++)
mainString[i] = CstyleString[i];
mainString[i] = '\0';
}
GString& Append(constchar* toAdd)
{
constint finalSize = size + strlen(toAdd);
char* finale = newchar[finalSize];
// Insert the original string characters (hell)
int j = 0;
for (j = 0; j < size; j++)
{
finale[j] = mainString[j];
}
// And now insert the characters of the string to append (o)
int k = j;
for (int i = 0; i < strlen(toAdd); k++, i++)
{
finale[k] = toAdd[i];
}
finale[k] = '\0';
return GString(finale);
}
This is the main:
1 2 3 4 5 6 7 8 9 10 11 12
int main()
{
GString my = "hell";
char* p = "o";
my = my.Append(p);
cout << my;
_getch();
return 0;
}
The cout should print "hello", instead... it prints "hell".