Being a noob to OOP and dynamic allocation, I am not sure if I am framing the question correctly. Anyway, here is the code. Note the constructor and destructor.
class Queue
{
int *array;
unsigned int siz;//Indicates how many elements are there right now
public:
void push(int);
void clear();
void print() const;
Queue(unsigned int len):array(new int[len]), siz(0) {} /*Constructor
indicating the maximum length*/
~Queue(){delete[] array;} //Destructor to free the memory
};
/*End of class definition */
void somefunction()
{
Queue sample(10); //Allocates memory from heap
.........
}
}
The Queue class contains an array and an unsigned integer indicating how many elements are there. The constructor takes an integer argument (indicating the maximum number of elements) and allocates space in the memory. The code works for my purpose whether I write the destructor or not, but I want to understand a bit of what is going on behind the scene when somefunction
creates a queue.
sample
itself is a local object, but it takes memory from the heap. So when sample
goes out of scope at the end of somefunction
what happens to the allocated memory if I
- write the destructor
- do not write the destructor
Do I need to write the destructor to avoid a memory leak? Also, if I do write it, does it get called automatically or do I need to somehow call it to ensure the memory is not leaked?
Also, what would be the role of the destructor if the class contained, for example, int array[10];
instead of int *array
? Could I just skip writing it then?