CMSC 202 Lesson 14 Copy and Assignment. Warmup Write the constructor for the following class: class CellPhone { public: CellPhone(int number, const string&

Slides:



Advertisements
Similar presentations
Chapter 18 Vectors and Arrays
Advertisements

Chapter 18 Vectors and Arrays John Keyser’s Modification of Slides by Bjarne Stroustrup
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.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Introduction to Programming Lecture 39. Copy Constructor.
1 Class Constructors a class constructor is a member function whose purpose is to initialize the private data members of a class object the name of a constructor.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Copy Control Joe Meehean. More Class Responsibilities When making a new type (i.e., class) we must specify what happens when it is: Copied Assigned Destroyed.
CMSC 202 Lesson 23 Templates II. Warmup Write the templated Swap function _______________________________ void Swap( ________ a, ________ b ) { _______________.
CMSC 202 Lesson 13 Pointers & Dynamic Memory. Warmup Overload the subtraction operator on two Money objects as a FRIEND! class Money { public: _______________.
Inheritance Joe Meehean. Object Oriented Programming Objects state (data) behavior (methods) identity (allocation of memory) Class objects definition.
CMSC 202 Lesson 19 Polymorphism 2. Warmup What is wrong with the following code? What error will it produce? (Hint: it already compiles) for (unsigned.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
C++ Review (3) Structs, Classes, Data Abstraction.
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+
1 Inside the Vector Class: with additional needed methods CPS212CPS212 Gordon College.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
More C++ Features True object initialisation
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
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.
Review of Last Lecture. What we have learned last lecture? What does a constructor do? What is the way to define a constructor? Can it be defined under.
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.
What happens... l When a function is called that uses pass by value for a class object like our dynamically linked stack? StackType MakeEmpty Pop Push.
CSI 3125, Preliminaries, page 1 Class. CSI 3125, Preliminaries, page 2 Class The most important thing to understand about a class is that it defines a.
Programming Languages and Paradigms C++. C++ program structure  C++ Program: collection of files Header files CPP source files  Files contain class,
Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Destructors The destructor fulfills the opposite functionality. It is automatically called when an object.
CMSC 202 Lesson 6 Functions II. Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout.
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.
Dynamic Memory Review l what is static, automatic, dynamic variables? Why are dynamic(ally allocated) variables needed l what is program stack? Function.
PROGRAMMING 1 – HELPER INSTRUCTIONS ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1.
1 // SPECIFICATION FILE (dynarray.h) // Safe integer array class allows run-time specification // of size, prevents indexes from going out of bounds, //
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.
On dynamic memory and classes ● We previously had only discussed dynamic memory in regards to structs and dynamic arrays. ● However, they can be used (to.
Yan Shi CS/SE 2630 Lecture Notes
Pointers and Classes.
Pointer to an Object Can define a pointer to an object:
Pointers and Dynamic Arrays
Learning Objectives Pointers as dada members
Default Constructors A default constructor is a constructor that takes no arguments. If you write a class with no constructor at all, C++ will write a.
Lesson 14 Copy and Assignment
Class: Special Topics Copy Constructors Static members Friends this
Memberwise Assignment / Initialization
CMSC 202 Lesson 21 Exceptions II.
group work #hifiTeam
CMSC 202 Templates.
Pointers & Dynamic Memory
Chapter 15-3 Pointers, Dynamic Data, and Reference Types
Polymorphism 2 CMSC 202.
A Deeper Look at Classes
CMSC 202 Lesson 6 Functions II.
CMSC 202 Lesson 19 Polymorphism 2.
Class: Special Topics 2 For classes using memory allocation
ENERGY 211 / CME 211 Lecture 30 December 5, 2008.
CMSC 202 Lesson 20 Exceptions 1.
Copy Constructors and Overloaded Assignment
C++ support for Object-Oriented Programming
Lesson 13 Pointers & Dynamic Memory
CMSC 202 Lesson 17 Inheritance II.
Presentation transcript:

CMSC 202 Lesson 14 Copy and Assignment

Warmup Write the constructor for the following class: class CellPhone { public: CellPhone(int number, const string& name ); private: int* m_number; string* m_name; };

Copying Objects… When do we make copies? Pass by value Return by value Assignment New object initialized with existing object Haven’t seen this….yet

Copy Constructor Initialize an object based on an existing object Examples: int a = 7; int b(a);// Copy constructor Shoe shoeOfMJ( “Nike”, 16 ); Shoe myShoe( shoeOfMJ );// Copy

Copy Constructor Use when dynamic memory is allocated Syntax: Prototype: ClassName( const ClassName& obj ); Implementation: ClassName::ClassName( const ClassName& obj ) { // code to dynamically allocate data }

Why do we care? Remember Assignment (by default) makes a direct copy of data members… With dynamic memory – this would be copying pointers Class int *data1 string *data2 Object *data3 7 abc Foo bar Class int *data1 string *data2 Object *data3

What do we want? Each object should have own memory allocated to members… Class int *data1 string *data2 Object *data3 7 abc Foo bar Class int *data1 string *data2 Object *data3 7 abc Foo bar

Example class Shoe { public: Shoe( const Shoe& shoe ); private: int *m_size; string *m_brand; }; Shoe::Shoe( const Shoe& shoe ) { m_size = new int( *shoe.m_size ); m_brand = new string( *shoe.m_brand ); } What’s going on here?

What else? Assignment Operator Define if using dynamic memory Syntax: Prototype: ClassName& operator=( const ClassName& obj ); Definition: ClassName& ClassName::operator=( const ClassName& obj ) { // Deallocate existing memory, if necessary // Allocate new memory }

What’s wrong with this? Shoe& Shoe::operator=( const Shoe& shoe ) { m_size = new int(*shoe.m_size); m_brand = new string(*shoe.m_brand); } // In main() Shoe a(7, “abc”); Shoe b(4, “edf”); b = a; Shoe a int *m_size string *m_brand 7 abc Shoe b int *m_size string *m_brand 4 edf What happened to the memory b was pointing to first???

What’s wrong with this? void Shoe::operator=( const Shoe& shoe ) { *m_size = *shoe.m_size; *m_brand = *shoe.m_brand; } Shoe a(7, “abc”); Shoe b(4, “edf”); Shoe c(9, “ghi”); c = b = a; How does the c = b work, when b = a returns nothing??

Fixed Shoe& Shoe::operator=( const Shoe& shoe ) { *m_size = *shoe.m_size; *m_brand = *shoe.m_brand; return *this; } Shoe a(7, “abc”); Shoe b(4, “edf”); Shoe c(9, “ghi”); c = b = a; What’s this? this – a pointer to the current object

Self-Assignment class RentalSystem { public: // Assume constructor, other methods… RentalSystem& operator=( const RentalSystem & rs ) private: Customer *m_customers; int m_nbrOfCustomers; }; RentalSystem& RentalSystem::operator=( const RentalSystem & rs ) { delete [] m_customers; m_customers = new Customer[rs.m_nbrOfCustomers]; for (int i = 0; i < rs.m_nbrOfCustomers; ++i) m_customers[i] = rs.m_customers[i]; return *this; } What happens when you do the following? RentalSystem r; // Add customers… r = r;

Protect from Self-assignment RentalSystem& RentalSystem::operator=( const RentalSystem & rs ) { // If this is NOT the same object as rs if ( this != &rs ) { delete [] m_customers; m_customers = new Customer[rs.m_nbrOfCustomers]; for (int i = 0; i < rs.m_nbrOfCustomers; ++i) m_customers[i] = rs.m_customers[i]; } return *this; }

Practice Implement copy constructor and = operator class Stapler { public: _______________// copy constructor _______________// operator= private: int *m_nbrStaples; };

Challenge Create a BoxOfStaplers class Implement copy constructor Implement operator= Hint: Take a look at the lecture notes for the SmartArray class!