Site hosted by Angelfire.com: Build your free website today!

 

 

next up previous contents
Next: Queues and Stacks derived Up: ConstructorsDestructors and Dynamic Previous: Destructors
 

 

Copy Constructors

When defining classes where the datafields include pointers, and memory is allocated dynamically, you really need to also define a copy constructor. This is a function that specifies how you should copy the fields. If you don't specify this, then whenever a class is copied (e.g., when using it as a call-by-value argument) it may not be copied right; datafields may point to an original version of some data, rather than a copy. This may cause weird errors.

When an object is copied, space is allocated for the contents of each datafield, so in the copy we'd have space for str and s. But no new space would be allocated for what str points to, and indeed that is not copied. This is called ``shallow'' copying, as only the top level is copied; the copied pointers in datafields will still point to the exact same bit of memory.

This is probably not what we want. And to avoid this we need to define a `copy constructor' that does a `deep' copy. Here's an example:

 

MyType::MyType(const MyType& another)
{
  int i;
  s = another.s;
  str = new char[s];
  for(i = 0; i<size; i++)
    str[i] = another.str[i];
}

This may be particularly important if we are going to use arguments of MyType as call-by-value arguments to functions:

 

myfn(MyType x)
{
  some stuff
}

(This is legal, but much more often you'd be dealing with pointers to objects of type MyType, or use call by reference).

Anyway, if you WERE using call-by-value then copies of the object would be created when the function was called. If you want call by value to behave as you would expect (not resulting in the parameter being modified when the fn exits) then you'd have to define a copy constructor.


 


 

Alison Cawsey
Fri Aug 28 16:25:58 BST 1998

 

1.     (lecture 20 Logic Programming) Ask to the data base created: Is there a swimmer who doesn’t like swimming?

 

check(X, Y) <=  job(X, Y) and not likes(X, Y).

 

2.     (lecture 20 Logic Programming) Specify in Prolog a rule that describes the relation grandparent ship between two persons.

 

Parent(a, b).

Parent(b, c).

 

grandparent(B,N):- parent(B,P),parent(P,N).

 

grandparent (a,n).

 

3.     (lecture 21 Functional Programming)

Specify in functional list notation (SCHEME LISP) the definition of a function that returns the sum of  n  integer numbers  sum(I), I=0, n.

 

(defun sum-of-list (lst)

           (cond ((null lst) 0)

                 (t (+ (first lst)

                       (sum-of-list (rest lst))))))

 

(defun summ (n)

  (cond

    ((<= n 0) 0)

    (t (+ n (summ (- n 1))))

  )

)

(define factorial (n) (

 

     (if (<= n 1) 1

 

        (* n (factorial (- n 1)))))