CS210 Lab: Operator Overloading Postlab

Postlab Exercise:

There are five questions to this postlab exercise.
  1. 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?

  2. 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.

  3. Given the following code segment, rewrite it to include the this pointer.
    class pwr 
    	double b;
    	int e;
    	double val;
    	pwr(double base, int exp);
    	double get_pwr() {return val;}
    pwr::pwr(double base, int exp)
    	if (exp==0) return;
    	for( ; exp>0; exp--) val=val * b;

  4. Why do overloaded operators which are defined as member functions only have one parameter, whereas those defined outside of the class have two parameters?

  5. In the lab exercise, you overloaded the << operator. Why would you use os instead of cout in the body of function?

  6. The myarray class in arrayadder2.cpp has 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.

    If you are using hercules, this error does not show up with g++ but it does with CC. 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?

For Answers, click here
Back to Operator Overloading Lab click here

CS Dept Home Page
CS Dept Class Files
CS210 Class Files

Copyright: Department of Computer Science, University of Regina.