myClass getClassFromFile(string filePath) {
Having a function return an instance of the class creates a copy of the class. When the copy is destroyed, it is calling your dtor which is delete[]ing your array.
When you have dynamically allocated stuff like this in your class, you need to write your own copy constructor and assignment operator, because the ones C++ gives you by default simply copy the pointer, and not the data the pointer points to.
- OR -
you could use a vector<string> instead of allocating by hand with new
- OR -
you could not return the value, but instead pass an object by reference so no copy occurs:
1 2
|
void getClassFromFile( myClass& cla_out, string filePath )
{ }
| |
(although writing a copy ctor and assignment operator would still be advised.
ALSO
you REALLY should have a default ctor for your class, which at least zeros the pointer so you don't attempt to delete[] something that hasn't been allocated. I also don't know how getClassFromFile is filling your myClass... but it shouldn't be allocating the buffer (myClass should be in charge of all of that).
But I'm going off on a tangent here. The solution to your problem is to write a copy constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class myClass
{
// ...
public:
// ...
// copy ctor
myClass( const myClass& rhs )
{
// << copy rhs to 'this' here >>
}
// assignment operator
myClass& operator = ( const myClass& rhs )
{
// << destroy 'this's current data, and replace it with rhs's data here >>
return *this;
}
};
| |
I'd also get rid of your copy() function, as it's somewhat flawed in that it fails to clean up any existing buffer, and it kind of poinless if you have proper copy ctors and assignment operators.
a.copy(&b); would be replaced with: a = b;