I'm sorry if this question was asked before. I searched the internet but couldn't find any clear answer.
Here is the issue :
Let's say I have a public class called Object that has 2 attributes. One is int attr1
and the other one is char * attr2
. The constructor is (I have a header file) :
Object::Object(int param1, char * param2)
{
attr1=param1;
attr2 = new char[strlen(param2)+1]; // I understand that by doing this the values are stored in the heap
strcpy(attr2, param2);
}
I understand that in the destructor of the class Object I need to write delete [] attr2
.
In another file, main.cpp I create a new object this way :
char * name = "Aname";
Object myObject = new Object(3, name);
From what I've understood, whenever new
is used, the value is stored in the heap. Therefore a delete
is necessary in order to avoid memory leaks.
Here I have used the new
operator to create an Object. Therefore myObject is a pointer to an Object stored in the heap. I will need to do this : delete myObject
when I will no longer need it.
So this is my question : since the object that myObject points to is stored in the heap, does that mean that all it's attributes are stored in the heap (including attr1
which is simply an int) ?
If so, how come I don't have to free it as well (meaning use the operator delete
for it in the destructor) ?
Thank you for you help!
Note : english is not my first language, sorry for the mistakes.