Automatics, Copy Constructor, and Assignment Operator

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Introduction to Programming Lecture 39. Copy Constructor.
A C LOSER L OOK AT C LASSES 1. A SSIGNING O BJECTS One object can be assigned to another provided that both objects are of the same type. It is not sufficient.
Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
CS 225 Lab #2 - Pointers, Copy Constructors, Destructors, and DDD.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Copy Constructors Fall 2008 Dr. David A. Gaitros
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
The Big Three Based on Weiss “Data Structures and algorithm Analysis CS240 Computer Science II.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
More C++ Features True object initialisation
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
Data Structures Using C++1 Chapter 3 Pointers Dr. Liu.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
The Assignment Operator. Rule of Three Any object which manages memory needs: – Custom Destructor – Custom Copy Constructor – Custom Assignment Operator.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Object Oriented Programming COP3330 / CGS5409.  Arithmetic Operator Overloading  Increment (++) / Decrement (--)  In-class exercise.
Memory Management.
Yan Shi CS/SE 2630 Lecture Notes
Pointer to an Object Can define a pointer to an object:
Pointers and Dynamic Arrays
Learning Objectives Pointers as dada members
Dynamic Memory Allocation
Andy Wang Object Oriented Programming in C++ COP 3330
Object Oriented Programming COP3330 / CGS5409
Constructor & Destructor
Class Operations Pointer and References with class types
Class: Special Topics Copy Constructors Static members Friends this
Memberwise Assignment / Initialization
This pointer, Dynamic memory allocation, Constructors and Destructor
Dynamic Memory Review what is static, automatic, dynamic variables? why are dynamic(ally allocated) variables needed what is program stack? function.
Dynamically Allocated Memory
understanding memory usage by a c++ program
Automatics, Copy Constructor, and Assignment Operator
Andy Wang Object Oriented Programming in C++ COP 3330
Advanced Program Design with C++
The Assignment Operator
Constructors and destructors
Copy Assignment CSCE 121 J. Michael Moore.
Destruction and Copying
Indirection.
CISC/CMPE320 - Prof. McLeod
Essential Class Operations
Destructor CSCE 121 J. Michael Moore.
CS148 Introduction to Programming II
COP 3330 Object-oriented Programming in C++
9-10 Classes: A Deeper Look.
Destructor CSCE 121.
Destruction and Copying
Andy Wang Object Oriented Programming in C++ COP 3330
COP 3330 Object-oriented Programming in C++
COP 3330 Object-oriented Programming in C++
Class: Special Topics 2 For classes using memory allocation
ENERGY 211 / CME 211 Lecture 30 December 5, 2008.
Essential Class Operations
Copy Assignment CSCE 121.
Destructors, Copy Constructors & Copy Assignment Operators
Rule of Three Part 1 & 2.
9-10 Classes: A Deeper Look.
Rule Of Three Part 3.
Copy Constructors and Overloaded Assignment
C++ support for Object-Oriented Programming
SPL – PS3 C++ Classes.
Presentation transcript:

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 don’t provide one Destructor // if you don’t provide one Copy Constructor Assignment operator=

Copy Constructor Just like a constructor Examples 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 = d Entry[5] heap (low address)

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

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

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 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)); 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; // don’t self copy // if you don’t 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/co pyconst/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; // don’t 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; } …

Fraction Example http://www.cs.fsu.edu/~myers/cop3330/examples/co pyconst/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) { return *this;