Reputation:
I was reading this post and I wanted to clarify, do I need to explicitly delete member variables of an object that has been created dynamically?
For example, I have a class with with two member variables,
class pointCloud
{
public:
pointCloud();
void addPoint(int);
point getPoint(int);
private:
int id;
std::vector<point> pointArray;
};
and then I create a dynamic instance of it in main...
int main()
{
pointCloud* cloud = new pointCloud;
cloud->addPoint(8);
delete cloud;
}
My understanding is that when delete cloud;
is called, the 'id' and 'pointArray' variables will automatically be deleted/freed from memory. Is this correct? Or will I need to write a destructor to explicitly delete those member variables?
Upvotes: 2
Views: 4392
Reputation: 6395
You do not need to delete the member variables - but you need to delete
the content of the pointArray, if you created it (with new
)
Generally, whatever you create (somewhere) with new
, you need to delete
also (somewhere); it is your problem to get that sorted out.
Here: you created pointCloud, and you deleted it. That's just fine.
Upvotes: 1
Reputation: 466
Or will I need to write a destructor to explicitly delete those member variables?
In your case no need to write, because id
is a primitive type, pointArray
is a vector which already has destructor which will free memory.
But, if you use raw pointers (allocate buffer via new[]), then in the destructor you have to manually free memory (delete[]).
Upvotes: 3