-
Take the code from Section 2 of this lab and add additional code to and
overload the "+" operator using arrays.
Hint: the prototype will look like the following:
int * operator+(int array1[MAXARRAY], int array2[MAXARRAY])
What happens when you compile this code?
-
In section 4, we introduced the concept of friend.
If we wanted to, we could rewrite the code for operator+
so that it doesn't need to access the value array directly.
How can we do that? Specify the new code.
-
Given the following code segment,
rewrite it to include the this pointer.
class pwr
{
double b;
int e;
double val;
public:
pwr(double base, int exp);
double get_pwr() {return val;}
};
pwr::pwr(double base, int exp)
{
b=base;
e=exp;
val=1;
if (exp==0) return;
for( ; exp>0; exp--) val=val * b;
}
-
Why do overloaded operators which are defined as member functions only have
one parameter, whereas those defined outside of the class have two parameters?
-
In the lab exercise, you overloaded the << operator.
Why would you use os instead of cout in the body of
function?
- In the lab exercise, your array had a fixed size. If you wanted a dynamic sized array you the first step might be to use a pointer to an array. This file: arrayadder2.cpp does that part for you, but now there's a problem when we make copies of the array...
This exercise is meant to review the concept of shallow versus deep copy.For a review on this
concept,
you can read about deep copy here and watch a video about deep copy here.
Your primary tasks for this exercise are:
- Modify the code so that you are doing a deep copy rather than a shallow
copy.
- See how this affects the printing of array3 and array4.
Steps include:
- Build and run the executable file (this is just to ensure that the
program is working). You should get the following output:
array1 array2 array3 array4
0 3 0 0
1 4 5 5
2 5 7 7
3 6 9 9
4 7 11 11
- Modify the code so that you are doing a deep copy. What is the change
in your output?
-
If you only modify the copy constructor, the myarray class in arrayadder2.cpp will have a memory leak. Freed objects do not free their arrays.
A simple destructor won't do. Because of the limited lifespan
of returned objects the memory allocated to temparray in operator+
is freed too soon. The copy constructor and the assignment
operator are not interchangeable and the default assignment is
shallow. So the memory leak cannot be plugged until there is both a
copy constructor and an assignment operator. This exercise is left
up to you.
This type of problem is hard to detect, especially if you are using hercules since this error does not always show up with g++. It crashes programs in Visual Studio.
Bonus: Consider the this pointer. What if you assign an object to
itself? What happens to the old array if you get new memory for the
array?