1 Classes Provide Constructors Mechanism to specify object creation Client can use objects similar to native types Constructor is member function with.

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

Object Oriented Programming COP3330 / CGS5409.  C++ Automatics ◦ Copy constructor () ◦ Assignment operator =  Shallow copy vs. Deep copy  DMA Review.
Chapter 7: User-Defined Functions II
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
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];
Chapter 14: Overloading and Templates
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Lecture 9 Concepts of Programming Languages
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.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
 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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
March 4, 2014CS410 – Software Engineering Lecture #9: C++ Basics III 1 Today’s Topics The operators new and deleteThe operators new and delete The scope.
Pointer Data Type and Pointer Variables
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
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.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
More about Class 靜宜大學資工系 蔡奇偉副教授 ©2011. 大綱 Instance Class Members Class members can be associated with an instance of the class or with the class as a.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
Chapter 10 Introduction to Classes
C++ Memory Overview 4 major memory segments Key differences from Java
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
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.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
LECTURE LECTURE 11 Constructors and destructors Copy constructor Textbook: p , 183.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
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 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Learners Support Publications Constructors and Destructors.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Memory Management.
Constructors and Destructors
Eine By: Avinash Reddy 09/29/2016.
Overloading Operator MySting Example
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.
Java Programming: Guided Learning with Early Objects
Java Primer 1: Types, Classes and Operators
CS410 – Software Engineering Lecture #11: C++ Basics IV
Constructor & Destructor
Lecture 9 Concepts of Programming Languages
Chapter 15 Pointers, Dynamic Data, and Reference Types
Chapter 9 Classes: A Deeper Look, Part 1
Chapter 15 Pointers, Dynamic Data, and Reference Types
Constructors and Destructors
CS410 – Software Engineering Lecture #5: C++ Basics III
More C++ Classes Systems Programming.
Lecture 9 Concepts of Programming Languages
Presentation transcript:

1 Classes Provide Constructors Mechanism to specify object creation Client can use objects similar to native types Constructor is member function with the same name as the class Constructs values of the class type Initializes data members Frequently, allocates free store using new

2 Getting Correct Memory for the Task “Where did I put that memory? I need more to get the job done.”

3 Built-in Operators new and delete new allocates memory from free store delete deal locates memory from free store Constructors often use new Destructors often use delete

4 Using new Initializer list Expressions used by the object's constructor or single value used for a native type p = new int(9); //pointer to int //initialized to 9 p = new int[9]; //pointer to 9 // element int array

5 Using Constructors and Destructors Constructors are more complicated May be overloaded and take arguments Constructor invoked Associated type used in definition Call-by-value used to pass value to a function Neither can use return statements Destructors implicitly invoked

6 Constructors & Destructors Form //can have multiple constructors class_name (parameter list); class_name (); //can have only 1 destructor ~class_name (); Constructors initializationstorage allocationconversions Destructors finalizationstorage reclamation

7 Constructors and the use of new Usually involve application of new new type-name optional-init-list new operator returns a pointer to base address of created object In the case of an array of objects, this is the address of its first element

8 Constructor Initialization (1 of 2) class mod_int { public: mod_int(int i) { v = i % modulus; } void assign(int i) { v = i % modulus; } void print() const { cout << v << '\t'; } const static int modulus; private: int v; }; const int mod_int::modulus = 60;

9 Constructor Initialization (2 of 2) int main() { int seconds = 400; mod_int z(seconds); //mod_int(int) cout << seconds << " seconds equals " << seconds / 60 << " minutes "; z.print(); cout << " seconds" << endl; return 0; }

10 Comments on the mod_int Program Integer v is restricted in value to 0, 1, 2,...modulus - 1 Programmer's responsibility to enforce this mod_int::mod_int() is constructor Invoked when objects of type mod_int are declared Function of one argument Requires expression assignment-compatible with int parameter to be passed to it Creates and initializes declared variable

11 Other mod_int Declarations mod_int a(0); // a.v = 0; mod_int b(61); // b.v = 1; but not mod_int a; // no parameter list mod_int c = 49; //construct mod_int(49) //and copy into c

12 The Default Constructor Constructor requiring no arguments Empty argument list or all arguments have default values Special purpose of initializing arrays of objects of its class

13 Multiple Constructors Convenient to overload constructor with several function declarations If no constructor, then arrays of objects automatically allocated by system If class has constructors but does not a default constructor, array allocation is syntactic error

14 Default Constructor with mod_int mod_int() { v = 0; } Possible to have the following declarations mod_int s1, s2; //init private v = 0 mod_int d[5]; //arrays initialized Empty parameter list constructor is invoked Could have one constructor serve as both general initializer and default constructor inline mod_int::mod_int(int i = 0) { v = i % modulus; }

15 Conversion Constructors Constructors of single parameter Used automatically for conversion unless declared with the keyword explicit Metal::Metal(Ore) provides code used to convert an Ore object to a Metal object Printable program prints invisible characters with their ASCII designation Code 07 (octal) is alarm or bel

16 Printable program (1 of 3) // ASCII printable characters // conversion constructor used class pr_char { public: pr_char(int i = 0) : c(i % 128) { } void print() const { cout << rep[c]; } private: int c; static const char* rep[128]; };

17 Printable program (2 of 3) const char* pr_char::rep[128] = { "nul", "soh", "stx", ·····// filled in with table of //ASCII characters "w", "x", "y", "z","{", "|", "}", "~", "del" };

18 Printable program (3 of 3) int main() { pr_char c; for (int i = 0; i (i); c.print(); cout << endl; } }

19 A Stack Whose Size can Vary

20 Constructing A Dynamically Sized Stack Constructor can allocate space from free store ch_stack’s length initialized by constructor ch_stack has hidden implementation detail Data members placed in private access region Public interface provides ch_stack abstraction Public member functions, such as push() and pop()

21 The Stack Functions Accessor functions do not change ch_stack object, such as top_of() and empty() Usual to make these const member functions Mutator functions change ch_stack object, such as push() and pop() Constructor member functions create and initialize ch_stack objects

22 Constructor Initializer (1 of 2) Special syntax for initializing sub-elements of objects with constructors Initializers for class members in comma-separated list following constructor parameter list Initialization replaces assignment Individual members must be initializable as member-name (expression list)

23 Constructor Initializer (2 of 2) When members are themselves classes with constructors, expression list is matched to appropriate constructor signature When non-static member is either const or reference, this form of member initialization is required

24 ch_stack Constructors (1 of 2) ch_stack::ch_stack() : max_len (100), top (EMPTY) { //default constructor s = new char[100]; assert(s); } ch_stack::ch_stack(int size) : max_len (size), top(EMPTY) { //specific size request assert(size > 0); s = new char[size]; assert (s); }

25 ch_stack Constructors (2 of 2) //domain transfer ch_stack::ch_stack(int size, const char str[]) : max_len(size) { int i; assert (size > 0); s = new char[size]; assert(s); for (i=0; i < max_len && str[i]!=0; ++i) s[i] = str[i]; top = — —i; }

26 Classes With Destructors Member function whose name is the same as class name preceded by a tilde Called implicitly When exiting block in which object was declared When delete operator called on pointer to object having destructor When deleting a subobject of an object

27 Using delete Destructors usually involve delete delete expression delete [] expression Pointer variable used in assignment from a new expression Brackets used when allocation involves a bracketed expression Array of objects are allocated off of free store Destructors called on each object stored in array

28 Problems with delete Deletion of zero-valued pointer is harmless Multiple deletions of same object is error System-dependent behavior results Deletion of pointer value not gotten from new expression is an error System-dependent behavior results

29 Destructor Details Implicitly invoked when object out of scope Block and function exit my_string sub_str(char c, string b) { //friend of my_string my_string substring; for (int i = 0; i <= b.len; ++i) if (c == s[i]) break; substring.assign(s + i); return substring; }

30 Comments on sub_str() b is call-by-value argument of type my_string Copy constructor invoked to create a local copy Destructor is called on function exit substring constructed upon block entry and destructor invoked on block exit Return argument constructed and passed back into calling environment Whether corresponding destructor is invoked depends on scope of object

31 A Destructor for ch_stack class ch_stack { public:... ~ch_stack() { delete [] s; }... };

32 Comments on ch_stack with Destructor External class interface remains the same Destructor invoked implicitly on block and function exit to clean up storage that is no longer accessible Good programming practice Programs execute with less memory

33 Using the Constructors //default creates s[100] ch_stack data; //creates N 100 element ch_stacks ch_stack d[N]; //N is 100 elsewhere //construct from my_string //w.s[0]='A'...w.s[3]='D' w.s[4] = 'A' ch_stack w(5, "ABCDA"); //constructs from existing ch_stack ch_stack x(w);

34 The Copy Constructor and call-by-value Examine ch_stack and count number of occurrences of a given character Repeatedly pop ch_stack, testing each element To preserve ch_stack, call-by-value int cnt_char(char c, ch_stack s) { int count = 0; while (!s.empty()) count += (c == s.pop()); return count; }

35 ch_stack and Copy Constructor OriginalCopyDuring Original ch_stackof OriginalPop ch_stack ch_stackOperations Preserved

36 The Default Copy Constructor Call-by-value requires that local copy of argument type be created and initialized from value of expression passed as actual argument Compiler provides a default copy constructor ch_stack::ch_stack(const ch_stack&); Compiler copies by memberwise initialization Default copy constructor may not work in all circumstances for complicated aggregates with members who are themselves pointers

37 Scope & Deletion in Copy Constructors In many cases, pointer is address of object deleted when going out of scope Duplicating pointer value but not object pointed at can lead to anomalous code Deletion affects other instances that still expect object to exist object

38 Making a Copy Constructor for ch_stack ch_stack::ch_stack(const ch_stack& str): max_len(str.max_len),top(str.top) { s = new char[str.max_len]; assert(s); memcpy(s, str.s, max_len); }

39 Garbage Collection for Reclaiming Memory list example shows system reclaiming memory by traversing each list and disposing of each element Reclamation is a form of garbage collection In LISP, Java, and C#, system itself is responsible for reclamation Systems periodically invoke garbage collector to identify all cells currently accessible and reclaim remaining inaccessible cells

40 Cheshire Cat Data Hiding Indirection provides data hiding Use of separate class for underlying data representation Cheshire Cat technique, in honor of Lewis Carroll’s cat that disappeared leaving only a smile This is a Design Pattern

41 Cheshire Cat Version of ch_stack class ch_stack { public: void reset() { ptr -> reset(); } void push(char c) { ptr->push(c); } char pop() { return ptr->pop(); } char top_of() const { return ptr->top_of(); } bool empty() const { return ptr -> empty(); } bool full() const { return ptr -> full(); } private: ch_stk_rep* ptr; // opaque pointer };

42 Cheshire Cat Comments All data and underlying operations handled through ch_stk pointer ch_stack is known as wrapper class Relationship between wrapper class and underlying representation class is called handle design pattern

43 Reference Counts “Don’t shut me off, fool, there are still 3 users attached!”

44 Reference Counting Each object tracks its active references On object creation, reference count set to one When object newly referenced, reference count incremented Each time object loses a reference, count decremented Delete object when reference count is zero

45 Reference Counting Semantics Underlying, frequently hidden, representation defined to include reference count Wrapper publicly delivers objects and tracks reference count Attention is paid to construction, destruction and assignment of object values

46 Reference Counted String Class (1 of 4) #include //check compiler #include class str_obj { public: int len, ref_cnt; char* s; str_obj() : len(0), ref_cnt(1) { s = new char[1]; s[0] = 0; } str_obj(const char* p) : ref_cnt(1) { len = strlen(p); s = new char[len + 1];strcpy(s, p); } ~str_obj() { delete []s; } };

47 Reference Counted String Class (2 of 4) class my_string { public: my_string() { st = new str_obj; } my_string(const char* p) { st = new str_obj(p); } my_string(const my_string& str) { st = str.st; st -> ref_cnt++; } ~my_string(); void assign(const my_string& str); void print() const { cout s; } private: str_obj* st; };

48 Reference Counted String Class (3 of 4) void my_string::assign(const my_string& str) { if (str.st != st) { if (--st -> ref_cnt == 0) delete st; st = str.st; st -> ref_cnt++; } This could be replaced by overloaded =

49 Reference Counted String Class (4 of 4) my_string::~my_string() { if (--st -> ref_cnt == 0) delete st; }

50 Comments on Reference Count (1 of 2) Client uses objects of type my_string Objects implemented as pointers st to values of type str_obj Copy constructor uses reference semantics

51 Comments on Reference Count (2 of 2) Anytime object's reference count is decremented, test for deletion Large aggregate copied by reference, with a small, fixed number of operations Reference counter uses small storage Change to pointer adds to reference count Destructor must test reference count

52 Assign() Semantics Semantics of assign() show subtleties Assignment occurs if my_string not being assigned its same value Assignment causes assigned variable to lose its previous value Equivalent to decrementing reference count of pointed-at str_obj value When reference count decremented, it gets tested for deletion

53 Advantages Large aggregate is copied by reference, using few operations and small amount of storage for reference counter Each possible change to pointer adds reference- count operation

54 Summary Class constructors and destructors manage storage Constructors can be used for copy and conversion Code destructors to get rid of memory if you use new to create object Reference counting semantics can help with large aggregates