Chapter 6 object creation and destruction

Source: Internet
Author: User
Chapter 6 object creation and
Destruction
• 6.1 classes with Constructors
• 6.1.1 the default constructor
• 6.1.2 constructor initializer
• 6.1.3 constructors
Conversions
• 6.2 constructing a dynamically
Sized Stack
• 6.2.1 the copy constructor
• 6.3 classes with Destructors
• 6.4 an example: dynamically
Allocated strings
• 6.5 aclassvect
• 6.6 members that are Class
Types
• 6.7 example: a singly linked
List
• 6.8 two-dimen1_arrays
• 6.9 polynomials as a linked
List
• 6.10 strings using reference
Semantics
• 6.11 no constructor. Copy
Constructor. and other
Mysteries
• 6.11.1 destructor details
• 6.12 pragmatics
• Summary
• Exercises
Chapter 6 object creation and
Destruction
• An object
A n obj e c t
Requires memory and some initial
Value. c ++ provides this through
Declarations that are definitions. In most
Cases, where we discuss declarations, we
Mean declarations that are definitions.
Chapter 6 object creation and
Destruction
• In creating complicated aggregates, the user will
Keep CT similar management of a class-defined
Object.
• A constructor
C o n s t r u C t o r
Is a member function whose name
Is the same as the class name; it constructs values
Of the class type. This process involves initializing
Data members and, frequently, allocating free store
Using new.
• A destructor
D e S t r u C t o r
Is a member function whose name is
The class name preceded by the Tilde character ~.
Its usual purpose is to destroy values of the class
Type, typically by using Delete.
Chapter 6 object creation and
Destruction
• Constructors are the more complicated of these
Two specially named member functions. They can
Be overloaded and can take arguments, neither
Which is possible for Destructors.
• A constructor is invoked when its associated Type
Is used in a definition; When call-by-value is used
To pass a value to a function, or when the return
Value of a function must create a value
Associated type.
• Destructors are invoked implicitly when an object
Goes out of scope.
• Constructors and Destructors do not have return
Types, and cannot use return expression
E x p r e s I o n
Statements.
6.1 classes with Constructors
• The simplest use of a constructor is
Initialization.
• Demo on page 168: modulo. cpp
-Using customized type
Mod_int A (0 );
-Initializing Value
6.1.1 The default constructor

Constructor requiring no arguments is
Called the default
De F Au l t
Constructor.
• It has the special purpose of initializing
Arrays of objects of its class.
Mod_int s l, S2; // both init private member V to 0
Mod_int d [5]; // arrays are properly initialized
6.1.1 The default constructor
• If a class does not have a constructor,
System provides a default constructor.
• If a class has constructors, but does not have
A default constructor, array allocation
Causes a syntactic Error
S y n t AC t I C E R or
.
• Notice that in our mod_int example one
Constructor cocould serve as both a general
Initializer and a default constructor:
6.1.2 constructor initializer
• There is a special syntax for initializing
Subelements of objects with constructors.
• Constructor
C On s t r u c t or
Initializers
I n I t I al I Z E R S
For structure and
Class Members can be specified in a commaseparated
List that follows the constructor
Parameter List and precedes the code body.
6.1.2 constructor initializer
• Notice how initialization replaces
Assignment. The individual members must
Be initializable:
Member-Name (expression List)
M e m be r-N am E (E xpr e s I on L I s t)
6.1.3 constructors as conversions
• Constructors of a single parameter are
Automatically conversion functions unless
Declared with the keyword explicit
E xpl I c I t
.
• Demo on Page 170: printabl. cpp
-Constructor creates an automatic conversion
-Conversions are covered in detail in Chapter 7
6.2 constructing a dynamically
Sized Stack
• A constructor can also be used to allocate space
From Free store.
• The design of the object ch_stack has des hidden
Implementation detail.
-Data members are placed in the private access region
Class ch_stack.
-The public interface provides clients with the expected
Stack operation action.
• Accessor
Functions:
Top_of () and empty ()
• Mutaror
Functions:
Such as push () and POP ().
• Constructor Member
• Demo on page 172: ch_stac4.h
6.2 constructing a dynamically
Sized Stack
• The corresponding function prototypes
Wocould be encoded as members of the class
Ch_stack. Let us use these constructors in
The following:
6.2.1 The copy constructor
• We wish to examine our stack and count
Number of occurrences of a given character.
We can repeatedly pop the stack, testing
Each element in turn, until the stack is
Empty. But what if we want to preserve
Contents of the stack?
6.2.1 The copy constructor
• The semantics of call-by-value require that
A local copy of the argument type be created
And initialized from the value of
Expression passed as the actual argument.
This requires a copy constructor.
C opy C on s t r u c t or.
Typename: typename (const
Tsceaoytnnpm
Typename
Eaytnpm
&);
6.2.1 The copy constructor
• The std1ib. h
S t d1i B. H
Routine memcpy () copies
Max_1en characters from the base address s
Tr. s into memory starting at base address S.
This is called a deep copy.
De e p c opy.
6.2.1 The copy constructor
• The character arrays are distinct because
They refer to different memory locations. If
Instead the body of this routine were
Shallow copy
S h a L O W C O P Y
6.3 classes with Destructors
• Destructors are member functions whose
Name is the class name preceded by a Tilde.
They are almost always called implicitly,
Usually at the exit of the block in which
Object was declared. They are also invoked
When a delete
De L E T E
Operator is called on a pointer
To an object having a destructor, or where
They are needed to destroy a subobject of
Object being deleted.
• Demo on page 175: ch_stack4.h
6.3 classes with Destructors
• The addition of the Destructor allows
Class to return unneeded heap-allocated
Memory during program execution.
6.4 an example: dynamically
Allocated strings
• A Native string type is lacking in C ++.
• An older style of string representation is
Pointer to Char.
• This use is reflected by the library.
.
String. h
S t r I N G. H
(Or
(Or
Cstring
C s t r I n g
In modern c ++ ).
I n m ode R n C + ).
• In modern c ++, the standard library string
Provides a string type that stores string
Length as part of its hidden implementation.
6.4 an example: dynamically
Allocated strings
• In this section, we shall develop some ways such
Type can be implemented, and also a useful string
ADT
That stores its length privately.
• The implementation will use the string. h
S t r I N G. H
Library
Functions to manipulate the underlying pointer
Representation of strings.
• Demo on page string5.cpp
-This type allows you to declare my_strings, assign
Copying one my_string to another, print a my_string,
And concatenate two my-strings.
6.4 an example: dynamically
Allocated strings
-Three overloaded Constructors
-Deconstructor
-Copy constructor
6.4 an example: dynamically
Allocated strings
• Copy constructor use
Tsceroyucu 1. A my_string is initialized by another mystring.
2. A my_string is passed as an argument in
Function.
3. A my_string is returned as the value of
Function.
6.4 an example: dynamically
Allocated strings
-The assignment semantics are based on deep
Copy semantics.
-This type allows you to declare my_strings,
Assign by copying one my_string to another,
Print a my_string, and concatenate two
My_strings.
6.4 an example: dynamically
Allocated strings
-This is a form of concatenation. Member
Functions have access not only to the private
Members of the implicit argument, but also
The private representation of any of
Arguments of Type my_string.
6.4 an example: dynamically
Allocated strings
-We deliberately used a variety of declarations
To show how different constructors wocould be
Called.
-The constructor my_string: my_string (const
Char *) is invoked to create and initialize
Objects A and author.
6.5 A Class vect
• The One-dimen1_array in C ++ is a very
Useful and efficient aggregate type.

Common mistake is to access elements
That are out of bounds. c ++ allows us
Control this problem by defining
Analogous container type in which bounds
Can be tested:
• Demo on Page 181: vect1.h
6.5 A Class vect
• The constructor vect: vect (int n) allows
The user to build dynamically allocated
Arrays.
• The constructor also initializes the variable
Size, whose value is the number of elements
In the array.
• Note that we declare this one-argument
Constructor explicit
E xpl I c I t
Because it is not intend
As an implicit conversion from I n t to vect.
6.5 A Class vect
• Access to individual elements is through
Safe indexing member function
Int & vect: element (int I)
• Accessed by the member function element:
6.5 A Class vect
• The ith
I t h
Element's address in the jth
J t h
Array
Wocould be given by a [J]. element (I
Il (]).
• In Chapter 11,
"Exceptions," we discuss how
Exceptions can be used to check on Error
Conditions.
6.6 members that are class types
• In this section we shall use the type vect
Tcve
As
A member of the class pair l-
Vect
Tcve
.
In OO
Methodology this is known as the hasa
Relationship. Complicated objects can be
Designed from simpler ones
Inconfigurating them with the hasa
Relationship.
• Demo on Page 183: pairvet. cpp
6.7 example: a singly linked list
• In this section, we develop a singly linked
List data type. This is the prototype of Parameter
Useful dynamic ADTs called selfs
E l f-
Eferential
E f e r e n t I al
Structures.
S t r u c t r e s.
• Demo on page 184: slist. cpp
6.7 example: a singly linked list
• List operations
1. prepend: add to front of list
2. First: return first element
3. Print: Print list Contents
4. DEL: Delete first element
5. Release: Destroy list
6.7 example: a singly linked list
6.7 example: a singly linked list
• The constructor initializes the head of s l I s
T pointer H to the value 0,
Which is called
Null Pointer constant
C On s t an t
And can be assigned
Any pointer type.
• Demo Summary
-Variable temp
-Use 0 assign to pointer
-Release Function
-Deconstructor
-Demonstrate the use of this type
6.8 two-dimen1_arrays
• Standard C does not have authentic
Multidimen1_arrays.
• In C ++ the programmer can implement
Flexible, safe, dynamic multidimensional
Arrays.
6.8 two-dimen1_arrays
• Type Matrix
6.8 two-dimen1_arrays
• How to Construct and desturct
6.9 polynomials as a linked list
• A polynomial is sparse
S PAR S E
When it has
Relatively few nonzero coefficients in
Comparison to its degree.
• Demo on page 191: ploy1.cpp
-The prepend () function links a term to the head
Of the list.
-The Reverse () function reverses a list in place.
-The add_term () function is used by plus ()
Add a next term and properly advance pointers
Within the two polynomials being added.
6.9 polynomials as a linked list
6.9 polynomials as a linked list
6.9 polynomials as a linked list
6.9 polynomials as a linked list
-Constructor member function
-Copy constructor member function
-Add_term member function
-Rest_of () member function
-Plus () member function
6.10 strings using reference
Semantics
• Allocation at run-time of large aggregates can
Readily exhaust memory resources.
• This model of reclamation is a form of garbage
G A R B A G E
Collection.
C o l e c t I o n.

Disposal Scheme that avoids this is reference
R e f e r e n C E
Counting.
C o u n t I n g.
Here, each dynamically allocated object
Tracks its active references. when an object is
Created, its reference count is set to one.
• The publicly used class my_string
Handles
Str_obj
Instances, and is sometimes called
Handler
H A n d l e r
Class.
6.10 strings using reference
Semantics
• Demo on page 197 string6.cpp
-Class str_obj
-Class my_string
-Member function assign ()
-My_string destructor
6.1 1 No constructor. Copy
Constructor. And other mysteries
• Object creation for native types is usually
The task of the compiler.
• Does every class need an explicitly defined
Constructor?
• Demo on page 200: Tracking. cpp
-What if we use constructors and allow the copy
Constructor to be default?
6.1 1 No constructor. Copy
Constructor. And other mysteries
• A destructor is implicitly invoked when
Object goes out of scope.
6.1 1 No constructor. Copy
Constructor. And other mysteries
• It is possible to explicitly call a destructor:
6.12 pragmatics
• In constructors, Initialization is to be
Preferred to assignment.
6.12 pragmatics
• As mentioned, data members that are
Reference declarations or const declarations
Must be initialized.
• In classes that use new to construct objects,
A copy constructor shoshould be explicitly
Provided.
6.12 pragmatics
• In cases where constructors of one
Argument are not intended as conversions,
C ++ has the recently added keyword
Explicit
E xpl I c I t
To disable its conversion semantics.
Summary
• 1. A constructor is a member function
Whose name is the class name.
• 2. A destructor is a member function whose
Name is the class name preceded by the Tilde
Character ~ .
• 3.
Constructor requiring no arguments is
Called the default constructor.
• 4.
Copy constructor of the form
Type:
: Type (const
Tsceoynp
Type &
X)
X)
Summary
• 5.
A class having members whose type
Requires a constructor uses initializers-
Comma-separated list of constructor cballs
Following a colon.
• 6. An efficient disposal scheme for large
Aggregates is reference counting.
• 7.
Constructors of a single parameter are
Automatically conversion functions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.