i am trying to make a vector class for exercise purpose but i am having trouble with memory management. |
Keep in mind that real C++ code would never do any of this: your name would be std::string, your data would be std::vector<double>, and you would not define a copy constructor, an assignment operator, or a destructor. You're not exercising a practical skill. Of course if you are really comfortable writing real C++, it may be worth exploring this dusty corner.
That said, the biggest errors are:
1. Vector::setName() calls
delete[] this->name;
, but when it is called from Vector's copy constructor, there's garbage in
this->name
2. Vector::getName and Vector::getData have no return statements when the condition is false
3. Vector::setData uses size instead of capacity in
double* arr = new double[size];
. The first call to v2.add will write to unallocated memory with
data[size++] = value;
4. memory leaks: the pointers returned by getName and getData are never freed.
It's worth rewriting this using at least the 1998 C++, or, better, modern C++.