Chapter3 Exercises&Solutions
Chapter3 Exercises&Solutions
intlist[10];
int *p;
the statement
p = list;
is valid in C++.
int *p;
the statement
p = new int[50];
dynamically allocates an array of 50 components of type int, and p contains the base address of the
array.
g. The address of operator returns the address and value of its operand.
int x;
int y;
int *p = &x;
int *q = &y;
*p = 35;
*q = 98;
*p = *q;
cout << x << " " << y << endl;
cout << *p << " " << *q << endl;
int num = 6;
int *p = #
a. p++;
b. (*p)++;
c. num++
d. (*num)++;
4. What is the output of the following code?
int *p;
int *q;
p = new int;
*p = 43;
q = p;
*q = 52;
p = new int;
*p = 78;
q = new int;
*q = *p;
int x;
int *p;
int *q;
p = new int[10] ; q = p;
*p = 4;
6. Explain the difference between a shallow copy and a deep copy of data.
7. What is the output of the following code?
int *p;
int *q;
p[0] = 5;
p[i] = p[i - 1] + 2 * i;
q = new int[5];
class dummyClass{
public:
void print();
...
...
private:
int listLength;
int *list;
double salary;
string name;
}
a. Write the function prototype to overload the assignment operator for the class
dummyClass.
b. Write the definition of the function to overload the assignment operator for the class
dummyClass.
c. Write the function prototype to include the copy constructor for the class dummyClass.
d. Write the definition of the copy constructor for the class dummyClass.
Solutions :
2. 98 98
98 98
3. b and c
4. 78 78
5. 4 4 5 7 10 14 19 25 32 40
6. In a shallow copy of data, two or more pointers points to the same memory space. In a
deep copy of data, each pointer has its own copy of the data.
7. Array p: 5 7 11 17 25
Array q: 25 17 11 7 5
9. The copy constructor executes when a variable is passed by value, when a variable is
declared and initialized using another variable, and when the return value of a function is an
object.
if(list !- NULL){
delete list;
}
list[j] = rightObject.list[j];
}
}
return *this;
}