Recitation Course 0520 Speaker: Liu Yu-Jiun.

Slides:



Advertisements
Similar presentations
Classes: A Deeper Look Systems Programming.  constconst  const objects and const member functions   Composition   Friendship  this  this pointer.
Advertisements

OOP Using Classes - I. Structures vs. Classes C-style structures –No “interface” If implementation changes, all programs using that struct must change.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 16: Classes and Data Abstraction Outline 16.1Introduction.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 16: Classes and Data Abstraction Outline 16.1Introduction 16.2Implementing a Time Abstract Data.
Classes: A Deeper Look Systems Programming.
Introduction to Classes and Data Abstraction
A Deeper Look at Classes CS-2303, C-Term A Deeper Look at Classes CS-2303 System Programming Concepts (Slides include materials from The C Programming.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
More C++ Classes Systems Programming. Systems Programming: C++ Classes 2 Systems Programming: 2 C++ Classes  Preprocessor Wrapper  Time Class Case Study.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
You gotta be cool. Access Functions and Utility Functions Preprocessor Wrapper Looking Ahead to Composition and Inheritance Object Size Class Scope and.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
Chapter 10 Classes: A Deeper Look, Part II Part I.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
 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.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 6: Classes and Data Abstraction Outline 6.1Introduction 6.2Structure Definitions 6.3Accessing.
CLASSES : A DEEPER LOOK Chapter 9 Part I 1. 2 OBJECTIVES In this chapter you will learn: How to use a preprocessor wrapper to prevent multiple definition.
Chapter 9 Classes: A Deeper Look, Part I Part II.
Class 4 (L34) u Constructors u Default Constructor u Example of Default Constructors u Destructors u Constructors Are Called in Global Scope u Constructors.
C++ Lecture 5 Monday, 18 July Chapter 7 Classes, continued l const objects and const member functions l Composition: objects as members of classes.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Review slides Mar 15, 2005.
Object Access m1.write(44); m2.write(m2.read() +1); std::cout
Chapter 16: Classes and Data Abstraction
Constructors and Destructors
Pointer to an Object Can define a pointer to an object:
Procedural and Object-Oriented Programming
IS Program Design and Software Tools Introduction to C++ Programming
Lecture 5: Classes (continued) Feb 1, 2005
CSC241: Object Oriented Programming
Chapter 16: Classes and Data Abstraction
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.
Chapter 9 More on Objects and Classes
Constructor & Destructor
Memberwise Assignment / Initialization
Chapter 17 - C++ Classes: Part II
group work #hifiTeam
Lecture 4: Classes (continued) June 14, 2004
Classes: A Deeper Look Outline
Lecture 5: Classes September 14, 2004
CS212: Object Oriented Analysis and Design
Chapter 9 Classes: A Deeper Look, Part 1
Operator Overloading; String and Array Objects
10.2 const (Constant) Objects and const Member Functions
Constructors and Destructors
Classes: A Deeper Look, Part 1
7.4 friend Functions and friend Classes
Classes: A Deeper Look, Part 2
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
9-10 Classes: A Deeper Look.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
Classes: A Deeper Look, Part 2
Classes: A Deeper Look, Part 1
A Deeper Look at Classes
Chapter 6: Classes and Data Abstraction
More C++ Classes Systems Programming.
9-10 Classes: A Deeper Look.
Presentation transcript:

Recitation Course 0520 Speaker: Liu Yu-Jiun

Reference: C++ How to Program 6e Destructors A special member function Name is the tilde character (~) followed by the class name, e.g., ~Time Called implicitly when an object is destroyed For example, this occurs as an automatic object is destroyed when program execution leaves the scope in which that object was instantiated Does not actually release the object’s memory It performs termination housekeeping Then the system reclaims the object’s memory So the memory may be reused to hold new objects 波浪符號表示解構子與建構子是相對的 離開物件的使用域時,系統會自動呼叫物件的解構子。不代表釋放了物件的記憶體空間,要到結束之後,系統才會回收物件佔用的空間,給其他物件使用。 Reference: C++ How to Program 6e

Reference: C++ How to Program 6e 9.7 Destructors (Cont.) Receives no parameters and returns no value May not specify a return type—not even void A class may have only one destructor Destructor overloading is not allowed If the programmer does not explicitly provide a destructor, the compiler creates an “empty” destructor 解構子沒有參數也沒有傳回值,而且一個類別只能有一個解構子,也不能overloading。跟建構子相同,使用者沒寫解構子,系統也會預設一個空的。 Reference: C++ How to Program 6e

9.8 When Constructors and Destructors Are Called Called implicitly by the compiler Order of these function calls depends on the order in which execution enters and leaves the scopes where the objects are instantiated Generally, Destructor calls are made in the reverse order of the corresponding constructor calls However, Storage classes of objects can alter the order in which destructors are called 物件的儲存類別會影響解構子的呼叫順序 Reference: C++ How to Program 6e

9.8 When Constructors and Destructors Are Called (Cont.) For an automatic local object Constructor is called when that object is defined Corresponding destructor is called when execution leaves the object’s scope For automatic objects Constructors and destructors are called each time execution enters and leaves the scope of the object Automatic object destructors are not called if the program terminates with an exit or abort function Reference: C++ How to Program 6e

9.8 When Constructors and Destructors Are Called (Cont.) For a static local object Constructor is called only once When execution first reaches where the object is defined Destructor is called when main terminates or the program calls function exit Destructor is not called if the program terminates with a call to function abort Global and static objects are destroyed in the reverse order of their creation Reference: C++ How to Program 6e

Prototype for destructor Reference: C++ How to Program 6e

Defining the class’s destructor Reference: C++ How to Program 6e

Reference: C++ How to Program 6e #include <iostream> #include "CreagAndDestroy.h" using namespace std; void create(void); CreateAndDestroy first(1, "(global before main)"); int main(){ cout << "\nMAIN FUNCTION: EXECUTION BEGINS" << endl; CreateAndDestroy second(2, "(local automatic in main)"); static CreateAndDestroy third(3, "(local static in main)"); create(); cout << "\nMAIN FUNCTION: EXECTION RESUMES" << endl; CreateAndDestroy fourth(4, "(local automatic in main)"); cout << "\nMAIN FUNCTION: EXECUTION ENDS" << endl; return 0; } void create(void){ cout << "\nCREATE FUNCTION: EXECUTION BEGINS" << endl; CreateAndDestroy fifth(5, "(local automatic in create)"); static CreateAndDestroy sixth(6, "(local static in create)"); CreateAndDestroy seventh(7, "(local automatic in create)"); cout << "\nCREATE FUNCTION: EXECUTION ENDS" << endl; Reference: C++ How to Program 6e

Reference: C++ How to Program 6e

9.8 When Constructors and Destructors Are Called (Cont.) For objects defined in global scope Constructors are called before any other function (including main) in that file begins execution The corresponding destructors are called when main terminates Function exit Forces a program to terminate immediately Does not execute the destructors of automatic objects Often used to terminate a program when an error is detected Function abort Performs similarly to function exit But forces the program to terminate immediately without allowing the destructors of any objects to be called Usually used to indicate an abnormal termination of the program 全域物件的建構子呼叫時間甚至比main function還早。 Main function終止的時候會呼叫相對應的解構子。 Exit:不會呼叫自動物件的解構子,程式發生執行錯誤時,利用exit function來終止程式。 Abort:不會呼叫任何物件的解構子,程式不正常結束執行。 Reference: C++ How to Program 6e

Reference: C++ How to Program 6e 9.9 Time Class Case Study: A Subtle Trap—Returning a Reference to a private Data Member Returning a reference to an object Alias for the name of an object An acceptable lvalue that can receive a value May be used on the left side of an assignment statement If a function returns a const reference That reference cannot be used as a modifiable lvalue One (dangerous) way to use this capability A public member function of a class returns a reference to a private data member of that class Client code could alter private data Same problem would occur if a pointer to private data were returned Reference: C++ How to Program 6e

Reference: C++ How to Program 6e #include <iostream> using namespace std; class Time{ public: Time(int = 0 , int = 0, int = 0); void setTime(int, int, int); int getHour(); int &badSetHour(int); private: int hour; int minute; int second; }; Time::Time(int hr, int min, int sec){ setTime(hr, min, sec); } void Time::setTime(int h, int m, int s){ hour = (h >= 0 && h < 24) ? h : 0; minute = (m >= 0 && m < 60) ? m : 0; second = (s >= 0 && s < 60) ? s : 0; int Time::getHour(){ return hour; Figure 9.14~9.15 Reference: C++ How to Program 6e

Reference: C++ How to Program 6e int &Time::badSetHour(int hh){ hour = (hh >= 0 && hh < 24) ? hh : 0; cout << "the address of hour is " << &hour << endl; return hour; } int main(){ Time t; int &hourRef = t.badSetHour(20); cout << "hourRef's content: " << hourRef << endl; cout << "hourRef's address: " << &hourRef << endl; hourRef = 30; cout << "\nInvalid hour after modification: " << t.getHour() << endl; t.badSetHour(12) = 74; cout << t.getHour() << endl; system("pause"); return 0; Figure 9.15~9.16 hourRef hour 74 12 20 30 Reference: C++ How to Program 6e

Result of Previous Code the address of hour is 0x23ff60 the content of hourRef: 20 the address of hourRef: 0x23ff60 Invalid hour after modification: 30 Another invalid hour seeting: 74 Reference: C++ How to Program 6e

9.10 Default Memberwise Assignment Assignment operator (=) Can be used to assign an object to another object of the same type Each data member of the right object is assigned to the same data member in the left object Can cause serious problems when data members contain pointers to dynamically allocated memory Reference: C++ How to Program 6e

Reference: C++ How to Program 6e Outline Date.h (1 of 1) Reference: C++ How to Program 6e

Reference: C++ How to Program 6e Outline Date.cpp (1 of 1) Reference: C++ How to Program 6e

Outline fig09_19.cpp (1 of 1) Memberwise assignment assigns data members of date1 to date2 date2 now stores the same date as date1 Reference: C++ How to Program 6e

9.10 Default Memberwise Assignment (Cont.) Copy constructor Enables pass-by-value for objects Used to copy original object’s values into new object to be passed to a function or returned from a function Compiler provides a default copy constructor Copies each member of the original object into the corresponding member of the new object (i.e., memberwise assignment) Also can cause serious problems when data members contain pointers to dynamically allocated memory Reference: C++ How to Program 6e

Chap 10

const object and const member function object declaring const class_name object_name; Function prototype return_type function_name ( p1, p2, ...) ; const 3 1 2 const const void help (const char * const p1); Reference: C++ How to Program 6e

const object and const member function (cont.) const member functions const objects are only allowed to call const member function Member functions declared const are not allowed to modify the object A function is specified as const both in its prototype and in its definition const declarations are not allowed for constructors and destructors Reference: C++ How to Program 6e

const object and const member function (cont.) const and reference data member不能使用賦值運算子(=),所以設定const資料成員的初始值得用成員初始值列表(member initializer list)。 Time::Time(int h, int m, int s) : hour(h), minute(m), second(s) {} const成員函式不可以更動任何成員資料的值。所以,如果成員函式不會更動資料成員的值,可以將成員函式設定為const。 const成員函式只能呼叫其它const成員函式。 Reference data member的話,得給一個變數名稱。 Reference: C++ How to Program 6e

10.3 Composition: Objects as Members of Classes Sometimes referred to as a has-a relationship A class can have objects of other classes as members Example class 機翼{ public: 機翼(int, int); void 轉彎(); int 修正飛行姿勢(int); private: int 寬度; int 長度; }; class 飛機{ public: 飛機(機翼, 機翼, int); private: 機翼 左機翼; 機翼 右機翼; int 載客數; }; int main(){ 機翼 big(3, 5); 飛機 747(big, big, 600); } 三次的機翼建構子呼叫,第一次是呼叫通用建構子,第二、三次是呼叫預設複製建構子;反之,也有三次的機翼解構子呼叫。 Reference: C++ How to Program 6e

Reference: C++ How to Program 6e Constructor Difference between default and general constructor Default Time (int = 0, int = 0, int = 0); Time () {hour = 0, minute = 0, second = 0} General Time (int, int, int); Reference: C++ How to Program 6e

10.4 friend Functions and friend Classes friend function of a class Defined outside that class’s scope Not a member function of that class Yet has the right to access the non-public (and public) members of that class Standalone functions or entire classes may be declared to be friends of a class Reference: C++ How to Program 6e

10.4 friend Functions and friend Classes (Cont.) To declare a function as a friend of a class: Provide the function prototype in the class definition preceded by keyword friend To declare a class as a friend of a class: Place a declaration of the form friend class ClassTwo; in the definition of class ClassOne All member functions of class ClassTwo are friends of class ClassOne 所有在classTwo的成員函式都是classOne的夥伴函式 Reference: C++ How to Program 6e

10.4 friend Functions and friend Classes (Cont.) Friendship is granted, not taken For class B to be a friend of class A, class A must explicitly declare that class B is its friend Friendship relation is neither symmetric nor transitive If class A is a friend of class B, and class B is a friend of class C, you cannot infer that class B is a friend of class A, that class C is a friend of class B, or that class A is a friend of class C It is possible to specify overloaded functions as friends of a class Each overloaded function intended to be a friend must be explicitly declared as a friend of the class Reference: C++ How to Program 6e

Outline fig10_15.cpp (1 of 2) friend function declaration (can appear anywhere in the class) Reference: C++ How to Program 6e

Outline fig10_15.cpp (2 of 2) friend function can modify Count’s private data Calling a friend function; note that we pass the Count object to the function Reference: C++ How to Program 6e

Reference: C++ How to Program 6e Using the this Pointer Outline fig10_17.cpp (1 of 2) Reference: C++ How to Program 6e

Outline fig10_17.cpp (2 of 2) Implicitly using the this pointer to access member x Explicitly using the this pointer to access member x Using the dereferenced this pointer and the dot operator Reference: C++ How to Program 6e

Cascaded member-function calls Outline Time.h (1 of 2) set functions return Time & to enable cascading Reference: C++ How to Program 6e

Reference: C++ How to Program 6e Outline Time.h (2 of 2) Reference: C++ How to Program 6e

Outline Time.cpp (1 of 3) Returning dereferenced this pointer enables cascading Reference: C++ How to Program 6e

Reference: C++ How to Program 6e Outline Time.cpp (2 of 3) Reference: C++ How to Program 6e

Reference: C++ How to Program 6e Outline Time.cpp (3 of 3) Reference: C++ How to Program 6e

Reference: C++ How to Program 6e Outline fig10_20.cpp (1 of 2) Cascaded function calls using the reference returned by one function call to invoke the next ((t.setHour(18)).setMinute(30)).setSecond(22); ((t).setMinute(30)).setSecond(22); ((t)).setSecond(22); Note that these calls must appear in the order shown, because printStandard does not return a reference to t Reference: C++ How to Program 6e

Reference: C++ How to Program 6e Outline fig10_20.cpp (2 of 2) Reference: C++ How to Program 6e