8
Copy Constructors Fall 2008 Dr. David A. Gaitros [email protected] .edu

Copy Constructors Fall 2008

  • Upload
    tam

  • View
    49

  • Download
    0

Embed Size (px)

DESCRIPTION

Copy Constructors Fall 2008. Dr. David A. Gaitros [email protected]. Automatic Functions. Functions automatically created for each class: Constructor: Creates objects Destructor: Deletes objects Copy Constructor Assignment operator = We have covered Constructor and Destructor. - PowerPoint PPT Presentation

Citation preview

Page 1: Copy Constructors Fall 2008

Copy ConstructorsFall 2008

Dr. David A. [email protected]

Page 2: Copy Constructors Fall 2008

Automatic Functions

• Functions automatically created for each class: – Constructor: Creates objects– Destructor: Deletes objects– Copy Constructor– Assignment operator =

We have covered Constructor and Destructor.

Page 3: Copy Constructors Fall 2008

Copy Constructor

• Copy constructor is a “constructor”• It is a function with the same name as

the class and no return type. • However, it is invoked implicitly– An object is defined to have the

value of another object of the same type.

– An object is passed by value into a function

– an object is returned by value from a function

Page 4: Copy Constructors Fall 2008

Copy Constructor

• Examples

Fraction f1, f2(3,4)

Fraction f3 = f2; // Copy Const.

f1 = f2; // Not a copy but assignment

// operator.

Page 5: Copy Constructors Fall 2008

Copy Constructor

• Declaring and Defining– A copy constructor always has one

(1) parameter, the original object. – Must be the same type as the

object being copied to. – Always passed by reference (must

be because to pass by value would invoke the copy constructor).

– Copy constructor not required

Fraction (const Fraction &f);

Timer (const timer & t);

Page 6: Copy Constructors Fall 2008

Copy Constructor

• Shallow copy vs deep copy– The default version is a shallow

copy. I.E. the object is copies exactly as is over to the corresponding member data in the new object location.

– Example: • Fraction f1(3,4);• The object example illustrates the

definition of an object f1 of type Fraction. • If passed as a parameter, a shallow

copy will be sufficient.

Page 7: Copy Constructors Fall 2008

Copy Constructor

• When there is a pointer to dynamic data, a shallow copy is not sufficient.

• Why? Because a default or shallow copy will only copy the pointer value (Address). Essentially both objects are pointing to the same item. Here we need a deep copy.

Page 8: Copy Constructors Fall 2008

Copy constructor

• Deep CopyDirectory::Directory (const Directory & d)

{

maxsize = d.maxsize;

currentsize = d.currentsize;

entryList = new Entry[d.maxsize];

for (int i=0; i<currentsize; i++)

entryList[i] = d.entryList[i];

}