C++ Quiz: Answers
The four special functions that may be generated by the compiler are:
- the default constructor
- the copy constructor
- the operator=() function
- the destructor
- X can define the member function operator Y()
- Y can define the constructor Y(const X&)
- c3 = c4 is an assignment
- C c1 = c2 is a copy-construction
Q1:
Element #0=32
Element #1=56
Element #2=2
Element #3=3
Element #4=4
Q1:
Element #0=32
Element #1=56
Element #2=2
Element #3=3
Element #4=4
arr destroyed for Q1
arr destroyed for Q1
The default
operator=() member function simply performs a "bitcopy". Thus after the assignment
q2 = q1 both objects hold a pointer to the same array. The solution involves overloading
operator=() and copying the array:
Qz4 &operator=(Qz4 &rh_q) {
if (&rh_q != this) { // make sure not a self assignment
seed = rh_q.seed;
delete arr; // delete old array
arr = new int[arr_l];
for(int i=0;i<arr_l;i++) set_arr(i, rh_q.get_arr(i));
}
return *this; // allow assignment chaining
}