I'm learning C++ and creating a simple class, tstring, defined by:
- n the number of characters in a string;
- ntotal the total number of characters in the tstring;
- p, pointer to a zone which contains the data.
Hence, this class is composed by a static part (n, ntotal and p) and by a dynamic part (the data itself).
I created three constructors :
*one without parameters; *one copy constructor; * one constructor which takes a C-string parameter.
I would like to be able to concatenate one tstring object with one C string, using for example the instructions:
tstring x("Hello), y;
y = x + " World";
To do this, I am overloading the +
operator as a non-member function.
However, when executing the following commands, all runs fine :
tstring x, y;
tstring z = x + y;
But when executing the following ones, I get a "pointer being freed was not allocated" error :
tstring x, y;
tstring z;
z = x + y;
I understand a little bit the logic behind that error but can not find a way to solve it.
Any help is welcome, thank you in advance!
You can find my implementation of the +
operator:
tstring operator+ (const tstring& myTstring1, const tstring& myTstring2)
{
tstring result;
result.n = myTstring1.nutile + myTstring2.n;
result.ntotal = myTstring1.ntotal + myTstring2.ntotal;
result.p = new char[result.ntotal];
for (int k = 0; k < maTstring1.n; ++k) {
result.p[k] = maTstring1.p[k];
}
for (int l = maTstring1.n; l < maTstring2.n; ++l) {
result.p[l] = maTstring2.p[l];
}
return result;
}
The constructor without parameter:
tstring::tstring(){
ntotal = 10;
n = 0;
p = new char[ntotal];
}
And the destructor:
tstring::~tstring(){
delete[] p;
}