CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=



Similar documents
CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

C++FA 5.1 PRACTICE MID-TERM EXAM

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

C++ INTERVIEW QUESTIONS

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Object Oriented Software Design II

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

C++ Overloading, Constructors, Assignment operator

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Curriculum Map. Discipline: Computer Science Course: C++

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Chapter One Introduction to Programming

CISC 181 Project 3 Designing Classes for Bank Accounts

13 Classes & Objects with Constructors/Destructors

Semantic Analysis: Types and Type Checking

An Incomplete C++ Primer. University of Wyoming MA 5310

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Advanced Data Structures

Comp151. Definitions & Declarations

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Passing 1D arrays to functions.

Object Oriented Software Design II

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Object Oriented Software Design II

The C Programming Language course syllabus associate level

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

1. Polymorphism in C++...2

Conversion Constructors

El Dorado Union High School District Educational Services

More C++ Concepts. Operator overloading Friend Function This Operator Inline Function

Chapter 2: Elements of Java

C++ Crash Kurs. C++ Object-Oriented Programming

Computer Programming C++ Classes and Objects 15 th Lecture

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES CONSTRUCTORS AND DESTRUCTORS

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

Sources: On the Web: Slides will be available on:

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Ch 7-1. Object-Oriented Programming and Classes

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

N3458: Simple Database Integration in C++11

J a v a Quiz (Unit 3, Test 0 Practice)

Member Functions of the istream Class

Constructor, Destructor, Accessibility and Virtual Functions

C++ Programming Language

Introduction to Programming Block Tutorial C/C++

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Formatting Numbers with C++ Output Streams

Object Oriented Software Design

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Binary storage of graphs and related data

Copy Constructors and Assignment Operators

Java (12 Weeks) Introduction to Java Programming Language

Subject Name: Object Oriented Programming in C++ Subject Code:

CS 111 Classes I 1. Software Organization View to this point:

Java Interview Questions and Answers

Certified PHP Developer VS-1054

Class 16: Function Parameters and Polymorphism

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Glossary of Object Oriented Terms

C++ Input/Output: Streams

Java Basics: Data Types, Variables, and Loops

Compiler Construction

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Basics of C++ and object orientation in OpenFOAM

Chapter 13 Storage classes

A Summary of Operator Overloading

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

Lecture 9. Semantic Analysis Scoping and Symbol Table

Answers to Review Questions Chapter 7

8.1. Example: Visualizing Data

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

C++ Language Tutorial

Note: Syntactically, a ; is needed at the end of a struct definition.

Appendix M: Introduction to Microsoft Visual C Express Edition

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

C++FA 3.1 OPTIMIZING C++

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Lecture 22: C Programming 4 Embedded Systems

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Appendix K Introduction to Microsoft Visual C++ 6.0

Common Beginner C++ Programming Mistakes

Variable Base Interface

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

5 Arrays and Pointers

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Transcription:

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= We already know that the compiler will supply a default (zero-argument) constructor if the programmer does not specify one. This default constructor will call each data member s default constructor in order to initialize the object. If the programmer wishes to override that default constructor, he or she simply provides one. There is another type of constructor the compiler generates it is called a copy constructor, and it's called whenever an object needs to be constructed from an existing one. Suppose we had a class to encapsulate strings, and we call this class mystring 1. It might include such data members as the length of the string as well as the characters that would be in the string. class mystring public: mystring(const char* s = ""); ~mystring(); ;... private: int length; char *str; For this example, we ll assume that the mystring constructor will allocate space for the characters, and the destructor will free that space. The copy constructor may be called when doing simple initializations of a mystring object: mystring me("geraldo"); mystring clone = me; // copy constructor gets called. More importantly, the copy constructor is called when passing an object by value, or returning an object by value. For instance, we might have a function which opens a file: static void openfile(mystring filename) // Convert the object to a character string, open a stream... 1 We re calling it mystring so we don t get confuse it with the built-in string class.

2 We might declare a string and call the OpenFile function like this: mystring name( flights.txt ); openfile(name); When passing the name object, the copy constructor is called to copy the mystring object from the calling function to the local parameter in the openfile function. Because we did not specify a copy constructor, the default copy constructor is called. Default Copy Constructor The default copy constructor does a member-wise copy of an object. For our mystring class, the default copy constructor will copy the length integer and the characters pointer. However, the characters themselves are not copied. This is called a shallow copy, because it only copies the data one level deep in a class hierarchy. In memory, what we d have would look like this: name filename This causes a problem because now the two objects share the same characters data. If we changed any of the characters within the filename object, it would change the characters in the name as well. What s worse is that after the OpenFile function exits, the mystring destructor is called on the filename object, which frees the characters data member. Now the name object has an invalid characters data member! What We Want: The Deep Copy In order to avoid potential disasters like this, what we want is a deep copy of the mystring object. We want a copy of the length, and we want a copy of the entire str data member not just a copy of the pointer.

3 What we want is a picture in memory which looks like this: name filename Now we can manipulate the characters within the filename object and not affect the original name object. When the character array within the copy is freed on exit the openfile function, the original mystring object is still going strong. Declaring a Copy Constructor In order to provide deep-copy semantics for our mystring object, we need to declare our own copy constructor. A copy constructor takes a constant reference to an object of the class type as a parameter and has no return type. We would declare the copy constructor for the mystring within the class declaration like this: class mystring public: mystring(const char* s = ); mystring(const mystring& s);... ; We might implement the copy constructor like this: mystring::mystring(const mystring& s) length = s.length; str = new char[length + 1]; strcpy(str, s.str); You should provide a copy constructor for any class for which you want deep copy semantics. If the class only has data members that are integral types (that is, it contains no pointers or open files) and/or direct objects (which have properly implemented copy constructors), you can omit the copy constructor and let the default copy constructor handle it.

Limitations The copy constructor is not called when doing an object-to-object assignment. For instance, if we had the following code, we would still only get a shallow copy: mystring betty( Betty Rubble ); // Initializes string to Betty Rubble mystring bettyclone; // Initializes string to empty string bettyclone = betty; This is because the assignment operator is being called instead of the copy constructor. By default, the assignment operator does a member-wise copy of the object, which in this case gives a shallow copy. However, C++ gives us the ability to override the default assignment operator, and we ll learn that today too. Incidentally, there may be cases when you want to prevent anyone from copying a class object via the copy constructor. By declaring a copy constructor as a private constructor within the class definition and not implementing it, the compiler will prevent the passing of objects of that class by value. Assignment It is possible to redefine the assignment operator for a class. The assignment operator must be defined as a member function in order to guarantee that the left-hand operand is an object. By default, the assignment operator is defined for every class, and it does a member-wise copy from one object to another. This is a shallow copy, so the assignment operator should generally be redefined for any class that contains pointers. You can declare the assignment operator as a private operator and not provide an implementation in order to prevent object-to-object assignment. The key difference between assignment and copy construction is that assignment possibly involves the destruction of embedded resources. We need to overload the assignment operator whenever we want to guarantee that memory (or perhaps other resources) aren't orphaned improperly. The syntax for the assignment method is a trifle quirky, but it's just that: syntax, and you just treat the prototype as boilerplate notation and otherwise implement the method as you would any other. const mystring& operator=(const mystring& rhs) if (this!= &rhs) delete[] this->str; // donate back useless memory this->str = new char[strlen(rhs.str) + 1]; // allocate new memory strcpy(this->str, rhs.str); // copy characters this->length = rhs.length; // copy length 4 return *this; // return self-reference so cascaded assignment works

A good way to look at the assignment operator: Think of it as destruction followed by immediate reconstruction. The delete[] would appear in the destructor as well, whereas the next three lines are very constructor-ish. 5 Caveats 1: Caveat 2: The this!= &rhs checks to see whether we're dealing with a selfassignment. An expression of the form name = name is totally legal, but there's no benefit in actually destroying the object only to reconstruct it only to take the same form. In fact, the delete[] line would actually release the very memory that we need on the very next line. The return type is const mystring&, and the return statement is return *this, because cascaded assignments involving mystrings should behave and propagate right to left just as they would with ints or doubles. mystring heroine("ginger"); mystring cluck("babs"); mystring quack("rhodes"); mystring meanie("mrs. tweety"); meanie = quack = cluck = heroine; cout << heroine << cluck << quack << meanie << endl; // should print: gingergingergingerginger