Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copy Constructors Fall 2008 Dr. David A. Gaitros

Similar presentations


Presentation on theme: "Copy Constructors Fall 2008 Dr. David A. Gaitros"— Presentation transcript:

1 Copy Constructors Fall 2008 Dr. David A. Gaitros dgaitros@admin.fsu.edu

2 Automatic Functions Functions automatically created for each class: – Constructor: Creates objects – Destructor: Deletes objects – Copy Constructor – Assignment operator = We have covered Constructor and Destructor.

3 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

4 Copy Constructor Examples Fraction f1, f2(3,4) Fraction f3 = f2; // Copy Const. f1 = f2; // Not a copy but assignment // operator.

5 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);

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

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

8 Copy constructor Deep Copy Directory::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]; }


Download ppt "Copy Constructors Fall 2008 Dr. David A. Gaitros"

Similar presentations


Ads by Google