Pages

July 26, 2010

Revew OOP244 - deep copy

In object-oriented programming, an object is not limited to the information stored in its own memory. An object can also access resources. A resource is information that is available to the object but is stored outside the object. The structure of such objects is described by classes with resources.

Resources

Resources include dynamic memory and files. These collections of information contain data that is stored outside the memory allocated to an object. An object keeps track of its resources through instance variables that hold the addresses of the resources. Such instance variables include

  • pointers to dynamic arrays in freestore memory
  • pointers to file structures
  • references
We call such instance variables resource instance variables.

To enable deep copying, we overwrite the compiler defaults for two member functions:

  1. the copy constructor
  2. the assignment operator

A copy constructor declaration takes the form

 Identifier ( const Identifier& );

Assignment Operator

The assignment operator is an operator that copies data from an existing object into an existing object. The compiler calls this operator whenever the compiler encounters an expression of the form

identifier = identifier where identifier is the name of an object.

The form of an assignment operator declaration is

Identifier& operator=(const Identifier&);

No Copies Allowed

In certain applications, it may be wise to avoid the making copies or assignments altogether. To prohibit the copying and the assigning of objects, we declare the copy constructor and the assignment operator as private members. For example,


class Student { int no; char* grade; Student(const Student& source); void operator=(const Student& source); public: Student(); Student(int, const char*); ~Student(); void display() const; };

No comments:

Post a Comment