14.4 Copy Constructors.

Slides:



Advertisements
Similar presentations
Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Advertisements

Operator overloading redefine the operations of operators
Lesson 14 Classes, Continued CS1 Lesson More Classes1.
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.
Contents o Introduction o Characteristics of Constructor. o Types of constructor. - Default Constructor - Parameterized Constructor - Copy Constructor.
Introduction to Programming Lecture 39. Copy Constructor.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Operator Overloading Fundamentals
CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Class and Objects.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 11 More.
Constructors & Destructors Review CS 308 – Data Structures.
Dynamic Memory for Class #include #ifndef STRCLASS_H_ #define STRCLASS_H_ class strclass { private: char *str; int len; static int num_strings; public:
Copy Constructors Shallow Copy: –The data members of one object are copied into the data members of another object without taking any dynamic memory pointed.
Operator Overloading CS 308 – Data Structures What is operator overloading? Changing the definition of an operator so it can be applied on the objects.
More About Classes Chapter Instance And Static Members instance variable: a member variable in a class. Each object has its own copy. static variable:
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
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+
C++ Lecture 4 Tuesday, 15 July Struct & Classes l Structure in C++ l Classes and data abstraction l Class scope l Constructors and destructors l.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Chapter 14 More About Classes. Chapter 13 slide 2 Topics 13.1 Instance and Static Members 13.2 Friends of Classes 13.3 Memberwise Assignment 13.4 Copy.
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.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
More C++ Features True object initialisation
Chapter 9 Classes: A Deeper Look, Part I Part II.
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.
Class and Structure. 2 Structure Declare using the keyword struct purpose is to group data Default visibility mode is public A struct doesn't have a constructor.
C++ Lecture 5 Monday, 18 July Chapter 7 Classes, continued l const objects and const member functions l Composition: objects as members of classes.
CSC241 Object-Oriented Programming (OOP) Lecture No. 5.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 5 1.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Using Member Functions and Data Members.
1 Memory as byte array Pointers Arrays relationship to pointers Operator ‘new’ Operator ‘delete’ Copy ctor Assignment operator ‘this’ const pointer Allocating.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 14: More About Classes.
Classes II Lecture 7 Course Name: High Level Programming Language Year : 2010.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
1 Ugly Realities The Dark Side of C++ Chapter 12.
Yan Shi CS/SE 2630 Lecture Notes
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
Pointers and Dynamic Arrays
Chapter 14: More About Classes.
Overloading Operator MySting Example
OBJECT ORIENTED PROGRAMMING
Concepts of Constructors and Its Types
Memberwise Assignment / Initialization
group work #hifiTeam
Chapter 14: More About Classes.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Object Oriented Programming (OOP) Lecture No. 9
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and Destructors
9-10 Classes: A Deeper Look.
Recitation Course 0520 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
A Deeper Look at Classes
Lab – 2018/04/12 implement getTotalCount to return how many ‘nMatrix’s are allocated(exist) (modify constructor and destructor, use static variable and.
CS 144 Advanced C++ Programming April 30 Class Meeting
9-10 Classes: A Deeper Look.
Chapter 8 Destructor (P.323) & Operator Overloading
SPL – PS3 C++ Classes.
Presentation transcript:

14.4 Copy Constructors

Copy Constructors Special constructor used when a newly created object is initialized to the data of another object of same class Default copy constructor copies field-to-field Default copy constructor works fine in many cases

Copy Constructors Problem: what if object contains a pointer? class SomeClass { public: SomeClass(int val = 0) {value=new int; *value = val;} int getVal(); void setVal(int); private: int *value; }

Copy Constructors What we get using memberwise copy with objects containing dynamic memory: SomeClass object1(5); SomeClass object2 = object1; object2.setVal(13); cout << object1.getVal(); // also 13 13 object1 object2 value value

Programmer-Defined Copy Constructor Allows us to solve problem with objects containing pointers: SomeClass::SomeClass(const SomeClass &obj) { value = new int; *value = obj.value; } Copy constructor takes a reference parameter to an object of the class

Programmer-Defined Copy Constructor Each object now points to separate dynamic memory: SomeClass object1(5); SomeClass object2 = object1; object2.setVal(13); cout << object1.getVal(); // still 5 5 13 object1 object2 value value

Programmer-Defined Copy Constructor Since copy constructor has a reference to the object it is copying from, SomeClass::SomeClass(SomeClass &obj) it can modify that object. To prevent this from happening, make the object parameter const: SomeClass::SomeClass (const SomeClass &obj)

MyString Design MyString class: Represent a sequence of characters the length of the string is important data member: s : pointer len methods: constructor: int n or char * length, print, destructor

Declare the Class my_string class MyString{ public: MyString(int n); MyString(const char * str); ~ MyString(); int length() const ; //const member function void print() const; private: char * s; int len; };

Constructors MyString :: MyString(int n) { s = new char[n+1]; s[0] = ‘\0'; len =n; } MyString :: MyString(const char * str) len = strlen(str); s = new char[len+1]; strcpy(s,str);

Overload Operator + (MyString) member function Prototype: MyString operator +(const MyString &b) const; Definition: MyString MyString ::operator+ (const MyString &b) const { cout << "member +" << endl; char * temp = new char[this->len + b.len +1]; strcpy(temp, this->s); strcat(temp, b.s); MyString str(temp); return str; }

Returning Local Object from a function Returning an object invokes the copy constructor while returning a reference doesn't. If a method or function returns a local object, it should return an object, not a reference. It is an error to return a pointer to a local object. Once the function completes, the local object are freed. The pointer would be a dangling pointer that refers to a nonexistent object.