I am studying for my midterm exam. There is going to be a question about setting up an array dynamically, and maybe doing a copy constructor, a destructor and overloading the assignment operator. Can you please verify if I am correct. Also I don’t understand what overloading the assignment operator means. Can you help me out with this?
class A { int* myArray; //basically I created a pointer called myArray, A() //are my copy constructors correct? A(), and A(int size)? { myArray = 0; } A(int size) { myArray = new int[size]; } ~A() // I think my destructor is correct { delete [] myArray; }
Can you check my code please? Also how do I overload assignment operator?
Thanks in advance.
The copy constructor is used for creation of object based on another’s instance of the same type. You don’t have such. You can define it using code like this:
You should change your class, so it will store _size of array, you also need to change visibility of your constructors and destructor to public.
The overloaded assignment operator should look like this:
You also can add a check of equality of array sizes in this assignment operator, so you will reuse your dynamic array without unnecessary reallocations of memory.