Hey I'm reviewing for a test I have in one of my classes and I'm looking at review questions from the book and from what the teacher said should be known for the test. I was hoping i could write the question then my answer and someone could tell me if i'm right or what needs to be added to know. I'll do a question at a time to make it easier.
When creating a class that uses dynamically allocated memory what three member functions must you provide besides the constructor. For each of the three know why it is necessary.
My answer is:
A class destructor, a deep copy operation, and a class copy-constructor are the three member functions needed. A destructor is necessary because it implicitly gets invoked when the class object is destroyed. A class object is destroyed when it goes out of scope. With a destructor the memory from the destroyed class object is deallocated freeing up space in the free store for other operations that require dynamic data to use. A deep copy operation is needed because when assigning one class object to another you want to copy not only the class members but also the data pointed to by the class object. This will leave two identical but separate class objects each with identical but separate class members and data. A copy-constructor is needed when there is only one class object to begin with and that one class object is initialized by another. With a copy constructor present a copy of a class object is made to a new class object identical to the first. Then when modifying the data of that object, you are actually working on a copy of the data, rather than the original. If there was no copy constructor present a new class object would be made but it would point to the same data as the original, thus when modifying the data in it you would be modifying the original data not a copy of it,which could make the data corrupt or useless.