class GString
{
private:
char* mainString;
int size;
public:
GString(constchar* CstyleString);
};
###
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';
}
The problem comes in the main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
// GArray of 1 GString... doesn't seem to have the \0 character at the end
GArray<GString> strs(1);
strs[0] = "test";
cout << strs[0] << endl;
// Simple GString... gets printed out correctly
GString test = "test";
cout << test;
_getch();
return 0;
}
The first cout prints "test" and after that it comes a random character, like: "testC", "test:".
But as you can see, in the constructor of GString, I do put a \0 at the end of the string.
In the second cout i can see the string without random characters...
It's like there's a problem with GString AND GArray.
I don't see how this could compile. This strs[0] is an attempt to use the subscript operator [] on the GArray<GString> object, but no such operator support has been written.
You also have no support for the << operator. I'm not convinced that this code compiles, so I've no idea what you're running to get the output that you see.
Your operator [] functions can complete without returning anything.
At least once you try to call the non-existent function Size() rather than the member size. Basically, what you have shown should repeatedly not compile.
I cannot see your screen. I cannot see the code you're trying to compile.
I have no idea what code you really are running, because the code you've shown does not compile.
In the constructor GArray(int) you feed the value NULL to the GString(const char*) constructor which requires a non-null pointer. The constructor dereferences that pointer resulting in undefined behavior.
Since GArray is meant to hold an arbitrary data type, why would you ever assign the pointer-value NULL to an element? Furthermore, why are you mixing the use of NULL and nullptr? Prefer the latter.
1 2 3 4
explicit GArray(int size)
: size(size), array_type(new GType[size]()) // <- note the extra parenthesis that value-initialize elements of an array.
{
}
And you should probably also change the constructor of GString to properly handle a nullptr value.
[edit: Also, your GString::operator=(const GString&) does not ensure the copied-to GString is 0-terminated. (Coincidentally, neither does the copy constructor.)]