Automatics, Copy Constructor, and Assignment Operator

Automatics, Copy Constructor, and Assignment Operator

Automatics, Copy Constructor, and Assignment Operator Andy Wang Object Oriented Programming in C++ COP 3330 Automatic Functions In C++, some default functions are automatically built Constructor // if you dont provide one

Destructor Copy Constructor Assignment operator= // if you dont provide one Copy Constructor Just like a constructor

Invoked implicitly when a COPY of an existing object is created; in particular, when An object is defined to have the value of another object of the same type An object is passed by value into function An object is returned (by value) from a function Examples Fraction f1, f2(3,4); Fraction f3 = f2; // a copy of f2 is created to initialize f3 f1 = f2; // calls the assignment operator, since f1 and f2 // already exist Declaring and Defining

A copy constructor creates a new object, initialized as a copy of another existing object Always has one parameter of the same type Passed by reference Since passing by value will invoke a copy constructor Format className(const className &); The const is not required, but a good idea for protecting the original

Example Fraction(const Fraction &f); Shallow vs. Deep Copy The default version makes a shallow copy Each member data location is copied Sufficient for classes like Fraction Only has a private numerator and denominator

May not be sufficient for pointer member data Example: Phonebook The entryList pointer will be copied and will point to the original dynamically allocated memory Deep Copy Creates a copy of dynamically allocated memory Directory::Directory(const Directory &d) { maxsize = d.maxsize; currentsize = d.currentsize; entryList = new Entry[d.maxsize]; for (int j = 0; j < currentsize; j++) entryList[j] = d.entryList[j];

} Visualize the Execution stack (high address) int main() { main heap (low address) Visualize the Execution stack (high address) int main() { Directory d; main

int maxSize = 5 int curentSize = 0 Entry *entryList = Entry[5] heap (low address) d Shallow Copy stack (high address) int main() { main Directory d; Directory d2 = d;

int maxSize = 5 int curentSize = 0 Entry *entryList int maxSize =5 = int curentSize = 0 Entry *entryList = Entry[5] heap (low address) d

Problems of Shallow Copy Potential inconsistencies Non dynamically allocated variables are copied Dynamically allocated variables point to the same memory region Double free

Runtime error Deep Copy stack (high address) int main() { main Directory d; Directory d2 = d; int maxSize = 5 int curentSize = 0 Entry *entryList int maxSize =5 =

int curentSize = 0 Entry *entryList = Entry[5] Entry[5] heap (low address) d Assignment Operator operator= is similar to the copy constructor Called when one object is assigned to another

Fraction f1, f2; f1 = f2; Assignment operator also has to make a copy The default version makes a shallow copy A deep copy needs to be overloaded by the user Copy Constructor vs. Assignment Operator Operator= Copy Constructor

Initializes a new object as a copy of an existing one Initialize data for the first time Has no return value Sets the current state of an object to that of

another existing object May need to free up old dynamically allocated memory Returns the value that was assigned, to support a = b = c = 4; Must be a member function

Chained Assignments a = b = c = 4; Same as a = (b = (c = 4)); Same as a = (b = 4); Thus, (c = 4) returns 4 by reference Need the ability to refer to an object from inside the object

The this pointer Inside a member function An object can access its own address using the this keyword To return the object itself by reference, return the target of the this pointer, or *this Like a copy constructor, operator= will take one

parameter of the same object type Examples Directory &operator=(const Directory &); Fraction &operator=(const Fraction &); Directory Operator= Implementation Directory &Directory::operator=(const Directory &d) { if (this == &d) return *this; // dont self copy // if you dont check this, this can self destruct delete [] entryList; maxsize = d.maxsize; currentsize = d.currentsize; entryList = new Entry[d.maxsize]; for (int j = 0; j < currentsize; j++)

entryList[j] = d.entryList[j]; return *this; } Phonebook Example http://www.cs.fsu.edu/~myers/cop3330/examples/ copyconst/phonebook/ directory.h #include entry.h class Directory { public: Directory(const Directory &); Directory& operator=(const Directory &);

private: }; directory.cpp Directory::Directory(const Directory &d) { maxsize = d.maxsize; currentsize = d.currentsize; entryList = new Entry[d.maxsize]; for (int j = 0; j < currentsize; j++) entryList[j] = d.entryList[j]; } directory.cpp Directory &Directory::operator=(const Directory &d) { if (this == &d) return *this; // dont self copy delete [] entryList;

maxsize = d.maxsize; currentsize = d.currentsize; entryList = new Entry[d.maxsize]; for (int j = 0; j < currentsize; j++) entryList[j] = d.entryList[j]; return *this; } menu.cpp Int main() { Directory d; d.Insert(); Directory d2 = d; // copy constructor d.DisplayDirectory(); d2.DisplayDirectory; d.Update(); d.DisplayDirectory(); d2.DisplayDirectory;

} Fraction Example http://www.cs.fsu.edu/~myers/cop3330/examples/ copyconst/frac/ No need for copy constructor and operator= Fraction does not have dynamically allocated memory Automatic versions are sufficient with the use of shallow copies frac.h class Fraction { public:

Fraction(const Fraction &f); Fraction &operator=(const Fraction &f); private: }; frac.cpp Fraction::Fraction(const Fraction &f) { numerator = f.numerator; denominator = f.denominator; } Fraction &Fraction::operator=(const Fraction &f) { numerator = f.numerator; denominator = f.denominator; return *this; }

Recently Viewed Presentations

  • Bellringer - ENGLISH 9 &amp; ACT PREP WITH MRS. THOMAS

    Bellringer - ENGLISH 9 & ACT PREP WITH MRS. THOMAS

    Bellringer. Trade your introductions with a neighbor. Rate your neighbor's paper on a scale of 1-3 based on the following: 1—the introduction does not capture the reader's attention, does not answer the prompt, and/or is missing key components of the...
  • IV. Electron Configuration

    IV. Electron Configuration

    "Empty Bus Seat Rule" C. Johannesson O 8e- Orbital Diagram Electron Configuration 1s2 2s2 2p4 B. Notation 1s 2s 2p C. Johannesson Shorthand Configuration (Noble-gas notation) S 16e- Valence Electrons Core Electrons S 16e- [Ne] 3s2 3p4 1s2 2s2 2p6...
  • Personality &amp; Travel - Ms. A de Boer

    Personality & Travel - Ms. A de Boer

    Personality & Travel. PsychocentricTravellers. ... Prefer a familiar tourist destination with accommodations, shops etc similar to those at home. ... Allocentric travelers view travel as a way of expressing inquisitiveness and curiousity.
  • Lotus Notes Support Top 10

    Lotus Notes Support Top 10

    GREAT NEW FEATURE!! SubAdmins can now easily export lists of student login ID's and passwords from the MyStudents tool, by clicking on the export CSV link in the upper-right corner of the browser window. No SubAdmin—request must be submitted to...
  • Mrs. Melanson Peek of the Week December 17th-21st

    Mrs. Melanson Peek of the Week December 17th-21st

    Mrs. Melanson. Peek of the Week. December 17th-21st. E-mail: [email protected] This is tentative and subject to change at any time without notice. This Week at a Glance
  • Successful Re-Entry: A Look at Getting Juvenile Offenders ...

    Successful Re-Entry: A Look at Getting Juvenile Offenders ...

    Project STAY OUT Overview. Goal 1: Build community capacity to serve young offenders w/ disabilities by providing training and PD to school personnel and JJ system Goal 2: Develop curriculum and training materials to support transition-related special educators in a...
  • Humanistisch christendom of christelijk humanisme,

    Humanistisch christendom of christelijk humanisme,

    Voor de wijzen uit de Spiltijd draaide religie om respect voor de heilige rechten van anderen [A] en niet om orthodox geloof. Als mensen zich vriendelijk en grootmoedig gedroegen tegenover anderen [A], konden ze de wereld redden… Wij moeten dit...
  • Service users opinions on how they have been affected by ...

    Service users opinions on how they have been affected by ...

    The food was superb" The End Suzanne Nash, Viewpoint www.hertsviewpoint.co.uk 01707 328014 Service users opinions on how they have been affected by changes to services Suzanne Nash Viewpoint Have services changed? In what ways have services changed for the worse?...