Chapter 8 Destructor (P.323) & Operator Overloading

Slides:



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

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.
Destructors Math 130 Lecture # xx Mo/Da/Yr B Smith: New lecture for 05. Use this for evolving to Java B Smith: New lecture for 05. Use this for evolving.
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
Lecture 12 Destructors “Absolute C++” Chapters 10.3, 15.2.
1 Chapter 7 Defining Your Own Data Types. 2 What Is a struct ?  A structure is a user-defined type You define it using the keyword struct so it is often.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
1 Chapter 8 Destructor & Operator Overloading. 2 Destructor  A destructor is a function that is called when an object is no longer required. A constructor.
C++ Review (3) Structs, Classes, Data Abstraction.
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 Management. Constructors –Compiler-generated –The Initializer List –Copy Constructors –Single-arg (conversion ctors) The Assignment Operator.
C++ Lecture 5 Monday, 18 July Chapter 7 Classes, continued l const objects and const member functions l Composition: objects as members of classes.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Destructors The destructor fulfills the opposite functionality. It is automatically called when an object.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
 Memory setup  Pointer declaration  Address operator  Indirection  Printing addresses or pointers.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
Object Access m1.write(44); m2.write(m2.read() +1); std::cout
1 Ugly Realities The Dark Side of C++ Chapter 12.
Constructors and Destructors
Pointer to an Object Can define a pointer to an object:
Pointers and Dynamic Arrays
論語 先進第十一 暮春者,春服既成 冠者五六人,童子六七人 浴乎沂,風乎舞雩,詠而歸 ㄧˊ 〔~河〕水名,源出中國山東省,至江蘇省入海。
By Muhammad Waris Zargar
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.
Chapter 9 More on Objects and Classes
CSC241: Object Oriented Programming
CS410 – Software Engineering Lecture #11: C++ Basics IV
Introduction to Classes
CMPE 135: Object-Oriented Analysis and Design October 17 Class Meeting
14.4 Copy Constructors.
This pointer, Dynamic memory allocation, Constructors and Destructor
Chapter 2 Objects and Classes
group work #hifiTeam
Dynamic Memory Allocation Reference Variables
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 16-2 Linked Structures
Introduction to Classes
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Constant pointers and pointers to constants
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and Destructors
Variables have attributes
9-10 Classes: A Deeper Look.
Introduction to Classes and Objects
Review Chapter 10 PPT for full coverage.
Arrays Arrays A few types Structures of related data items
Recitation Course 0520 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
Classes: A Deeper Look, Part 1
C++ Programming Lecture 20 Strings
Review: C++ class represents an ADT
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Destructors, Copy Constructors & Copy Assignment Operators
Pointers, Dynamic Data, and Reference Types
Destructors, Copy Constructors & Copy Assignment Operators
Chapter 8 (Part 2) Destructor & Operator Overloading (P.331)
送孟浩然之廣陵 ~李白 故人西辭黃鶴樓, 煙花三月下揚州。 孤帆遠影碧空盡, 惟見長江天際流。.
CS 144 Advanced C++ Programming April 30 Class Meeting
9-10 Classes: A Deeper Look.
Video: The Sound of Raining
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
4.1 Introduction Arrays A few types Structures of related data items
Data Structures & Programming
Presentation transcript:

Chapter 8 Destructor (P.323) & Operator Overloading

Destructor A destructor is a function that is called when an object is no longer required. A constructor is a function which is called when a new object is created. A constructor is usually used to initiate an object. A destructor is usually used to destroy an object.

The Default Destructor The destructor for a class is a member function with the same name as the class, preceded by a tilde (~). For the CBox class, the prototype of the clas destructor is ~CBox(); A destructor has no parameters. Ex8_01.cpp on P.324 ~CBox() { cout << "Destructor called." << endl; }

A Simple Example (cf. P.324) 3 a 5 b class CData { public: int* pdata; CData(int n=0) pdata = new(int); *pdata = n; cout << "Constructor called with initial value " << n << endl; } ~CData() cout << "Destructor called to release the memory storing " << *pdata << endl; delete pdata; }; int main() CData a(3); CData b(5); return 0; 3 a 5 b Constructor called with initial value 3 Constructor called with initial value 5 Destructor called to release the memory storing 5 Destructor called to release the memory storing 3

Class CMessage (1) P.326 Suppose you want to define a class Each object contains a text string. You don’t want to declare a data member as a large character array (like char [200]), So you’ll allocate memory in the free store for the message when an object is created. This is your constructor: CMessage(const char* text = "Default message") { m_pMessage = new char[strlen(text) + 1]; strcpy(m_pMessage, text); }

strlen, strcmp, strcpy #include <iostream> #include <cstring> using std::cout; using std::endl; int main() { char a[20] = "NCNU"; char b[20] = "Sunday"; cout << sizeof a << " " << strlen(a) << endl; // size = 20, string length = 4 if (strcmp(a,b) < 0) cout << "The string " << a << " is less than " << b << endl; strcpy(a, b); cout << a << endl; }

Destructors and Dynamic Memory Allocation (P.326) CMessage(const char* text = "Default message") { m_pMessage = new char[strlen(text) + 1]; strcpy_s(m_pMessage, strlen(text)+1, text); } ~CMessage() cout << "Destructor called." << endl; delete [] m_pMessage; A miss is as good as a mile. A cat can look at a queen. Destructor called. Write down this sentence on P.328: When some data members are dynamically allocated (see Chapter 4), a destructor must be used to destroy an object and release the memory. Q: What is the size of an object of the CMessage class?

Ex8_02.cpp on P.328 A miss is as good as a mile. A cat can look at a queen. Destructor called. As the output indicates, the destructor is called only once. The object motto is created automatically, so the compiler also calls the destructor automatically. If you did not manually “delete pM”, it wouldn’t free the memory pointed to by pM. Because the pointer pM points to a CMessage object, the delete operation causes the destructor to be invoked. Output becomes A miss is as good as a mile. A cat can look at a queen. Destructor called.

Q: Why Should I Write My Destructor? Why isn’t C++ compiler smart enough to automatically release the memory pointed by the pointer in my object? Consider some more complicated cases: 3 a 5 b c d

Dynamic Allocation Causes Troubles Not Only for Destructors class CData { public: int* pdata; CData(int n=0) pdata = new(int); *pdata = n; cout << "Constructor called with initial value " << n << endl; } void Print() cout << *pdata << endl; }; int main() CData a(3); CData b = a; a.Print(); b.Print(); *(a.pdata) = 5; 3 a 5 3 3 b 5 5

Q: What will the second motto2.ShowIt() display? CMessage motto1("A stitch in time saves nine."); CMessage motto2(motto1); motto2.ShowIt(); // Display 2nd message strcpy(motto1.m_pMessage, "Time and tide wait for no man."); motto1.ShowIt(); // Display 1st message Exercise: Let’s run figure8-1.cpp, but please ignore the run-time error message at this moment. (Explained in next slides)

Behavior of a Default Copy Constructor CMessage motto1(“Radiation fades your genes.”); CMessage motto2(motto1); // Calls default copy constructor FIGURE 8-1 (P.330)

Implementing a Copy Constructor (P.329) We don’t want the two objects sharing the same string in the memory. If motto1 is destroyed, the pointer in motto2 will become invalid. Let us implement a copy constructor to generate an object which is identical but independent of the old one. CMessage(const CMessage& aMess) // P.330 { m_pMessage = new char [ strlen(aMess.m_pMessage) +1 ]; strcpy(m_pMessage, aMess.m_pMessage); } Exercise: Modify Ex8_02.cpp (P.328) to implement this copy constructor.