Object Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The 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.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
AU/MITM/1.6 By Mohammed A. Saleh 1. Arguments passed by reference  Until now, in all the functions we have seen, the arguments passed to the functions.
Winter 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assn 4 posted shortly. Demonstrate a memory leak problem using the assignment 4 solution. Back to.
Class and Objects.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Classes Separating interface from implementation
Using Templates Object-Oriented Programming Using C++ Second Edition 11.
OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
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.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
Pointer Data Type and Pointer Variables
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Object-Oriented Programming in C++
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
 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
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
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.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
1 Using Templates COSC 1567 C++ Programming Lecture 10.
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.
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.
1 Introduction to Object Oriented Programming Chapter 10.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
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.
Constructors and Destructors
Pointers and Dynamic Arrays
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 7 CS 3370 chapter 7 CS 3370 – C++ Classes.
CS410 – Software Engineering Lecture #11: C++ Basics IV
Class: Special Topics Copy Constructors Static members Friends this
group work #hifiTeam
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
CS212: Object Oriented Analysis and Design
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and Destructors
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
9-10 Classes: A Deeper Look.
Java Programming Language
CS410 – Software Engineering Lecture #5: C++ Basics III
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Destructors, Copy Constructors & Copy Assignment Operators
Destructors, Copy Constructors & Copy Assignment Operators
9-10 Classes: A Deeper Look.
Presentation transcript:

Object Management

Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator

Constructors Execute after an object is created –Used to initialize an object –Doesn’t implicitly create anything Which constructor runs depends on arguments –Overload resolution Run after sub-objects are initialized –Base class and sub-objects initialize first Example: initMembers.cpp

The Initializer List Member objects are default-initialized –Unless you specify otherwise Via the initializer list The only way to initialize const members It is inefficient and poor practice to initialize member objects in the body of the containing constructor –Built-in types okay, though Examples: badInit.cpp, goodInit.cpp, constMem.cpp

Pseudo-constructors For built-in types Used to zero-initialize scalar variables Gotcha: prototype syntax Example: initInt.cpp

A String Class #include class String { char* data; public: String(const char* s = "") { data = new char[std::strlen(s) + 1]; std::strcpy(data,s); } ~String() {delete [] data;} int size() const {return std::strlen(data);} char getAt(int pos) const {return data[pos];} void setAt(int pos, char c) const {data[pos] = c;} void display() { std::cout << data; } };

Using class String int main() { String s = "hello"; // same as String s("hello"); for (int i = 0; i < s.size(); ++i) cout << "s[" << i << "] == " << s.getAt(i) << std::endl; String empty; std::cout << '"'; empty.display(); std::cout << "\"\n"; } /* Output: s[0] == h s[1] == e s[2] == l s[3] == l s[4] == o "" */

Strange Behavior int main() { String s = "hello"; String t = s;// same as String t(s); t.setAt(0,'j'); s.display(); } /* Output: jello <The instruction at “0x004022dd” referenced memory at “0x ”. The memory could not be “written”. */

Initialization vs. Assignment Initialization occurs only once, when an object is created always by some constructor Assignment occurs only after an object has been initialized via operator= What constructor executed in the previous slide?

The Copy Constructor Initializes a new object as a copy of an existing object –of the same type Has signature T::T(const T&) –or T::T(T&) Copies each member across –using their own copy constructors recursively Generated by compiler –But you can override it (and sometimes should)

Compiler-generated Copy Ctor String(const String& s) : data(s.data) {} // Identical to: String(const String& s) { data = s.data; } // because pointers are not objects.

“Shallow Copy” hello\0 s::data t::data

If you have a pointer as a data member, a shallow copy is probably not what you want By changing the referent in one object, you also change it in the other object If you de-allocate the data member in one object, you have created a likely fatal situation in the other (double delete) Problems with Shallow Copy

What should the Copy Ctor Do? Make a “Deep Copy”: –Allocate new heap space –Copy characters to target

A “Deep Copy” Copy Constructor // You must do this when you need deep copy: String(const String& s) { data = new char[strlen(s.data)+1]; strcpy(data, s.data); }

Passing Objects by Value Rarely done Objects are often returned by value, though A copy is made –Therefore, a constructor executes –Which constructor?

Which Constructor? Not always the copy constructor Depends on the argument(s) –As simple as that! Example: trace.cpp

More Strange Behavior Why does changing t affect s below? int main() { String s = "hello";// same as String s(“hello”); String t; t = s; t.setAt(0) = 'j'; cout << s << endl; } jello

Object Assignment Uses operator= must be a member Generated by the compiler assigns individual members String::operator= just assigns the pointer data but we want to replicate the underlying characters! You can override it and should whenever an object’s state is external to itself a pointer (or reference) member is a sign that operator= needs help

Compiler-generated Assignment String& String::operator=(const String& rhs) { data = rhs.data; return *this; } hello\0 s t

What should String::operator= Do? Allocate new heap space Copy characters to target Delete the old heap space Return *this Avoid unnecessary self-assignment –And watch the order you do things in!

Correct Assignment String& String::operator=(const String& s) { if (&s != this) { char* new_data = new char[strlen(s.data)+1]; strcpy(new_data, s.data); delete [] data; data = new_data; } return *this; }

Prohibiting Copy and Assignment Make the copy constructor and assignment operator private –Will cause a compile error if client code tries to copy or assign Only declare them –Define no function bodies –Will cause a link error if member functions try to copy or assign

Standard Conversions Implicit promotion of numeric types Widening of: –char -> short -> int -> long Promotion from integer to floating-point Occurs in mixed-mode expressions (x + i) and in passing parameters –Prototypes initiate the conversion for parms

Implicit Conversions to Class Type Achieved through a single-argument constructor –Also called a “converting constructor” –Or less commonly, through a conversion operator (will see later) You can turn it off –With a special keyword (explicit)

Limitations Sometimes multiple conversions occur in sequence in a single expression Only one class type (i.e., non-primitive) is allowed inside a sequence of conversions Example –convert.cpp –convert2.cpp

Turning off Implicit Conversions explicit keyword Applies only to single-arg constructors Example –convert3.cpp

Object Management Summary Copy Constructor the compiler generates it only if you don’t does shallow copy All Other Constructors if you don’t provide any constructors at all, the compiler generates a default constructor (which default-constructs each member) Single-arg constructors are special (“conversion constructors”) Assignment Operator the compiler generates it only if you don’t does shallow assignment Destructor the compiler generates only if you don’t (calls each member’s destructor)