SlideShare a Scribd company logo
Classes and Objects
Lecture 2
Introduction
• Object-oriented programming (OOP)
– Encapsulation: encapsulates data (attributes) and
functions (behavior) into packages called classes
– Information hiding : implementation details are
hidden within the classes themselves
• Classes
– Classes are the standard unit of programming
– A class is like a blueprint – reusable
– Objects are instantiated (created) from the class
– For example, a house is an instance of a “blueprint
class”
Implementing a Time Abstract Data
Type with a Class
• Classes
– Model objects that have attributes (data
members) and behaviors (member functions)
– Defined using keyword class
– Have a body delineated with braces ({ and })
– Class definitions terminate with a semicolon
– Example:
1 class Time {
2 public:
3 Time();
4 void setTime( int, int,
int );
5 void printMilitary();
6 void printStandard();
7 private:
8 int hour; // 0 - 23
9 int minute; // 0 - 59
10 int second; // 0 - 59
11 };
Public: and Private: are
member-access specifiers.
setTime, printMilitary, and
printStandard are member
functions.
Time is the constructor.
hour, minute, and
second are data members.
Implementing a Time Abstract Data
Type with a Class
• Member access specifiers
– Classes can limit the access to their member functions and data
– The three types of access a class can grant are:
• Public — Accessible wherever the program has access to an object of
the class
• private — Accessible only to member functions of the class
• Protected — Similar to private and discussed later
• Constructor
– Special member function that initializes the data members of a
class object
– Cannot return values
– Have the same name as the class
Objects
• Class definition and declaration
– Once a class has been defined, it can be used as
a type in object, array and pointer declarations
– Example:
Time sunset, // object of type Time
arrayOfTimes[ 5 ], // array of Time objects
*pointerToTime, // pointer to a Time object
&dinnerTime = sunset; // reference to a Time object
Note: The class name
becomes the new type
specifier.
1 // Fig. 6.3: fig06_03.cpp
2 // Time class.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // Time abstract data type (ADT) definition
9 class Time {
10 public:
11 Time(); // constructor
12 void setTime( int, int, int ); // set hour,
minute, second
13 void printMilitary(); // print military
time format
14 void printStandard(); // print standard
time format
15 private:
16 int hour; // 0 – 23
17 int minute; // 0 – 59
18 int second; // 0 – 59
19 };
20
21 // Time constructor initializes each data member to
zero. 22 // Ensures all Time objects start in a consistent
state. 23 Time::Time() { hour = minute = second = 0; }
24
25 // Set a new Time value using military time.
Perform validity
26 // checks on the data values. Set invalid values to
zero. 27 void Time::setTime( int h, int m, int s )
28 {
29 hour = ( h >= 0 && h < 24 ) ? h : 0;
30 minute = ( m >= 0 && m < 60 ) ? m : 0;
31 second = ( s >= 0 && s < 60 ) ? s : 0;
32 }
Note the :: preceding
the function names.
33
34 // Print Time in military format
35 void Time::printMilitary()
36 {
37 cout << ( hour < 10 ? "0" : "" ) << hour << ":"
38 << ( minute < 10 ? "0" : "" ) << minute;
39 }
40
41 // Print Time in standard format
42 void Time::printStandard()
43 {
44 cout << ( ( hour == 0 || hour == 12 ) ? 12 :
hour % 12 )
45 << ":" << ( minute < 10 ? "0" : "" ) <<
minute 46 << ":" << ( second < 10 ? "0" : "" ) <<
second 47 << ( hour < 12 ? " AM" : " PM" );
48 }
49
50 // Driver to test simple class Time
51 int main()
52 {
53 Time t; // instantiate object t of class Time
54
55 cout << "The initial military time is ";
56 t.printMilitary();
57 cout << "nThe initial standard time is ";
58 t.printStandard();
59
60 t.setTime( 13, 27, 6 );
61 cout << "nnMilitary time after setTime is ";
62 t.printMilitary();
63 cout << "nStandard time after setTime is ";
64 t.printStandard();
65
66 t.setTime( 99, 99, 99 ); // attempt invalid
settings 67 cout << "nnAfter attempting invalid settings:"
68 << "nMilitary time: ";
69 t.printMilitary();
70 cout << "nStandard time: ";
71 t.printStandard();
72 cout << endl;
73 return 0;
74 }
The initial military time is 00:00
The initial standard time is 12:00:00 AM
Military time after setTime is 13:27
Standard time after setTime is 1:27:06 PM
After attempting invalid settings:
Military time: 00:00
Standard time: 12:00:00 AM
Implementing a Time ADT with a Class
• Destructors
– Functions with the same name as the class but preceded
with a tilde character (~)
– Cannot take arguments and cannot be overloaded
– Performs “termination housekeeping”
• Binary scope resolution operator (::)
– Combines the class name with the member function
name
– Different classes can have member functions with the
same name
• Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){
…
}
• If a member function is defined inside the
class
– Scope resolution operator and class name are not
needed
– Defining a function outside a class does not
change it being public or private
• Classes encourage software reuse
– Inheritance allows new classes to be derived from
old ones
Implementing a Time ADT with a Class
Class Scope and Accessing Class
Members
• Class scope
– Data members and member functions
• File scope
– Nonmember functions
• Inside a scope
– Members accessible by all member functions
• Referenced by name
• Outside a scope
– Members are referenced through handles
• An object name, a reference to an object or a pointer to an object
Class Scope and Accessing Class
Members
• Function scope
– Variables only known to function they are defined in
– Variables are destroyed after function completion
• Accessing class members
– Same as structs
– Dot (.) for objects and arrow (->) for pointers
– Example:
• t.hour is the hour element of t
• TimePtr->hour is the hour element
1 // Fig. 6.4: fig06_04.cpp
2 // Demonstrating the class member access
operators . and ->
3 //
4 // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC
DATA! 5 #include <iostream>
6
7 using std::cout;
8 using std::endl;
9
10 // Simple class Count
11 class Count {
12 public:
13 int x;
14 void print() { cout << x << endl; }
15 };
16
17 int main()
18 {
19 Count counter, // create counter
object 20 *counterPtr = &counter, // pointer to
counter 21 &counterRef = counter; // reference to
counter 22
23 cout << "Assign 7 to x and print using the
object's name: ";
24 counter.x = 7; // assign 7 to data member
x 25 counter.print(); // call member function
print 26
27 cout << "Assign 8 to x and print using a
reference: ";
28 counterRef.x = 8; // assign 8 to data member
x 29 counterRef.print(); // call member function
print 30
31 cout << "Assign 10 to x and print using a
pointer: ";
32 counterPtr->x = 10; // assign 10 to data member
x
33 counterPtr->print(); // call member function
print
34 return 0;
35 }
Assign 7 to x and print using the object's name: 7
Assign 8 to x and print using a reference: 8
Assign 10 to x and print using a pointer: 10
Controlling Access to Members
• public
– Presents clients with a view of the services the class
provides (interface)
– Data and member functions are accessible
• private
– Default access mode
– Data only accessible to member functions and
friends
– private members only accessible through the
public class interface using public member
functions
1 // Fig. 6.6: fig06_06.cpp
2 // Demonstrate errors resulting from attempts
3 // to access private class members.
4 #include <iostream>
5
6 using std::cout;
7
8 #include "time1.h"
9
10 int main()
11 {
12 Time t;
13
14 // Error: 'Time::hour' is not accessible
15 t.hour = 7;
16
17 // Error: 'Time::minute' is not accessible
18 cout << "minute = " << t.minute;
19
20 return 0;
21 }
Compiling...
Fig06_06.cpp
D:Fig06_06.cpp(15) : error C2248: 'hour' : cannot access private
member declared in class 'Time'
D:Fig6_06time1.h(18) : see declaration of 'hour'
D:Fig06_06.cpp(18) : error C2248: 'minute' : cannot access private
member declared in class 'Time'
D:time1.h(19) : see declaration of 'minute'
Error executing cl.exe.
test.exe - 2 error(s), 0 warning(s)
Attempt to access private member
variable minute.
Attempt to modify private member
variable hour.
Class definition
class class_name {
public:
constructor and destructor
member functions
private:
data members
};
Initializing Class Objects: Constructors
• Constructors
– Initialize class members
– Same name as the class
– No return type
– Member variables can be initialized by the constructor or
set afterwards
• Passing arguments to a constructor
– When an object of a class is declared, initializers can be
provided
– Format of declaration with initializers:
Class-type ObjectName( value1,value2,…);
– Default arguments may also be specified in the
constructor prototype
1 // Fig. 6.8: time2.h
2 // Declaration of the Time class.
3 // Member functions are defined in time2.cpp
4
5 // preprocessor directives that
6 // prevent multiple inclusions of header file
7 #ifndef TIME2_H
8 #define TIME2_H
9
10 // Time abstract data type definition
11 class Time {
12 public:
13 Time( int = 0, int = 0, int = 0 ); // default
constructor
14 void setTime( int, int, int ); // set hour,
minute, second
15 void printMilitary(); // print military
time format
16 void printStandard(); // print standard
time format
17 private:
18 int hour; // 0 - 23
19 int minute; // 0 - 59
20 int second; // 0 - 59
21 };
22
23 #endif
61 // Fig. 6.8: fig06_08.cpp
62 // Demonstrating a default constructor
63 // function for class Time.
64 #include <iostream>
65
66 using std::cout;
67 using std::endl;
68
69 #include "time2.h"
70
71 int main()
72 {
73 Time t1, // all arguments defaulted
74 t2(2), // minute and second
defaulted 75 t3(21, 34), // second defaulted
76 t4(12, 25, 42), // all values specified
77 t5(27, 74, 99); // all bad values specified
78
79 cout << "Constructed with:n"
80 << "all arguments defaulted:n ";
81 t1.printMilitary();
82 cout << "n ";
83 t1.printStandard();
84
85 cout << "nhour specified; minute and second
defaulted:"
86 << "n ";
87 t2.printMilitary();
88 cout << "n ";
89 t2.printStandard();
90
91 cout << "nhour and minute specified; second
defaulted:"
92 << "n ";
93 t3.printMilitary();
OUTPUT
Constructed with:
all arguments defaulted:
00:00
12:00:00 AM
hour specified; minute and second defaulted:
02:00
2:00:00 AM
hour and minute specified; second defaulted:
21:34
9:34:00 PM
hour, minute, and second specified:
12:25
12:25:42 PM
all invalid values specified:
00:00
12:00:00 AM
When only hour
is specified,
minute and
second are set
to their default
values of 0.
94 cout << "n ";
95 t3.printStandard();
96
97 cout << "nhour, minute, and second specified:"
98 << "n ";
99 t4.printMilitary();
100 cout << "n ";
101 t4.printStandard();
102
103 cout << "nall invalid values specified:"
104 << "n ";
105 t5.printMilitary();
106 cout << "n ";
107 t5.printStandard();
108 cout << endl;
109
110 return 0;
111 }
Using Destructors
• Destructors
– Are member function of class
– Perform termination housekeeping before the system
reclaims the object’s memory
– Complement of the constructor
– Name is tilde (~) followed by the class name (i.e.,
~Time)
• Recall that the constructor’s name is the class name
– Receives no parameters, returns no value
– One destructor per class
• No overloading allowed
When Constructors and Destructors Are
Called
• Constructors and destructors called automatically
– Order depends on scope of objects
• Global scope objects
– Constructors called before any other function (including main)
– Destructors called when main terminates (or exit function
called)
– Destructors not called if program terminates with abort
• Automatic local objects
– Constructors called when objects are defined
– Destructors called when objects leave scope
• i.e., when the block in which they are defined is exited
– Destructors not called if the program ends with exit or abort
• Static local objects
– Constructors called when execution reaches the
point where the objects are defined
– Destructors called when main terminates or
the exit function is called
– Destructors not called if the program ends with
abort
When Constructors and Destructors Are
Called
Ad

More Related Content

Similar to Classes and objects constructor and destructor (20)

classes and constructors lec 03 & 04.ppt
classes and constructors lec 03 & 04.pptclasses and constructors lec 03 & 04.ppt
classes and constructors lec 03 & 04.ppt
meome111
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
VGaneshKarthikeyan
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
VGaneshKarthikeyan
 
Operator overload rr
Operator overload  rrOperator overload  rr
Operator overload rr
Dhivya Shanmugam
 
Csphtp1 08
Csphtp1 08Csphtp1 08
Csphtp1 08
HUST
 
C++ L08-Classes Part1
C++ L08-Classes Part1C++ L08-Classes Part1
C++ L08-Classes Part1
Mohammad Shaker
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
farhan amjad
 
Object oriented design
Object oriented designObject oriented design
Object oriented design
lykado0dles
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
FALLEE31188
 
Data Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self ReferentialData Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self Referential
babuk110
 
OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++ OBJECT ORIENTED PROGRAMING IN C++
OBJECT ORIENTED PROGRAMING IN C++
Dev Chauhan
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Introduction to Fundamental of Class.pptx
Introduction to Fundamental of Class.pptxIntroduction to Fundamental of Class.pptx
Introduction to Fundamental of Class.pptx
DawitTekie1
 
Chapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptxChapter 2 OOP using C++ (Introduction).pptx
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
Object orinted programming lecture| Variables
Object orinted programming lecture| VariablesObject orinted programming lecture| Variables
Object orinted programming lecture| Variables
cenaj3443
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
Kongunadu College of Engineering and Technology
 
Classes and object
Classes and objectClasses and object
Classes and object
Ankit Dubey
 
Unit i
Unit iUnit i
Unit i
snehaarao19
 
oops-1
oops-1oops-1
oops-1
snehaarao19
 

More from areebakanwal12 (12)

Streaming and input output mOOPlec9.pptx
Streaming and input output mOOPlec9.pptxStreaming and input output mOOPlec9.pptx
Streaming and input output mOOPlec9.pptx
areebakanwal12
 
SE lect2_2.pptxv model design software models
SE lect2_2.pptxv model design software modelsSE lect2_2.pptxv model design software models
SE lect2_2.pptxv model design software models
areebakanwal12
 
ENERGEYCRISES ARE THE LARGEST SINGLE DRAIN ON PAKISTAN ECONOMY.pptx
ENERGEYCRISES ARE THE LARGEST SINGLE DRAIN ON PAKISTAN ECONOMY.pptxENERGEYCRISES ARE THE LARGEST SINGLE DRAIN ON PAKISTAN ECONOMY.pptx
ENERGEYCRISES ARE THE LARGEST SINGLE DRAIN ON PAKISTAN ECONOMY.pptx
areebakanwal12
 
02-7 Habits for successLecture review.pptx
02-7 Habits for successLecture review.pptx02-7 Habits for successLecture review.pptx
02-7 Habits for successLecture review.pptx
areebakanwal12
 
presentationeerrrrrrrr-190220050301.pptx
presentationeerrrrrrrr-190220050301.pptxpresentationeerrrrrrrr-190220050301.pptx
presentationeerrrrrrrr-190220050301.pptx
areebakanwal12
 
Parallel computing and programming of parallel environment
Parallel computing and programming of parallel environmentParallel computing and programming of parallel environment
Parallel computing and programming of parallel environment
areebakanwal12
 
Web Engineering Process Models- An introduction.pptx
Web Engineering Process Models- An introduction.pptxWeb Engineering Process Models- An introduction.pptx
Web Engineering Process Models- An introduction.pptx
areebakanwal12
 
professional ethics about ethical values in workplace
professional ethics about ethical values in workplaceprofessional ethics about ethical values in workplace
professional ethics about ethical values in workplace
areebakanwal12
 
turing machine theory and making process.pptx
turing machine theory and making process.pptxturing machine theory and making process.pptx
turing machine theory and making process.pptx
areebakanwal12
 
Classes and objects object oriented programming
Classes and objects object oriented programmingClasses and objects object oriented programming
Classes and objects object oriented programming
areebakanwal12
 
SE_Requirement Engineering Process Models
SE_Requirement Engineering Process ModelsSE_Requirement Engineering Process Models
SE_Requirement Engineering Process Models
areebakanwal12
 
Data encapsulation and information hiding
Data encapsulation and information hidingData encapsulation and information hiding
Data encapsulation and information hiding
areebakanwal12
 
Streaming and input output mOOPlec9.pptx
Streaming and input output mOOPlec9.pptxStreaming and input output mOOPlec9.pptx
Streaming and input output mOOPlec9.pptx
areebakanwal12
 
SE lect2_2.pptxv model design software models
SE lect2_2.pptxv model design software modelsSE lect2_2.pptxv model design software models
SE lect2_2.pptxv model design software models
areebakanwal12
 
ENERGEYCRISES ARE THE LARGEST SINGLE DRAIN ON PAKISTAN ECONOMY.pptx
ENERGEYCRISES ARE THE LARGEST SINGLE DRAIN ON PAKISTAN ECONOMY.pptxENERGEYCRISES ARE THE LARGEST SINGLE DRAIN ON PAKISTAN ECONOMY.pptx
ENERGEYCRISES ARE THE LARGEST SINGLE DRAIN ON PAKISTAN ECONOMY.pptx
areebakanwal12
 
02-7 Habits for successLecture review.pptx
02-7 Habits for successLecture review.pptx02-7 Habits for successLecture review.pptx
02-7 Habits for successLecture review.pptx
areebakanwal12
 
presentationeerrrrrrrr-190220050301.pptx
presentationeerrrrrrrr-190220050301.pptxpresentationeerrrrrrrr-190220050301.pptx
presentationeerrrrrrrr-190220050301.pptx
areebakanwal12
 
Parallel computing and programming of parallel environment
Parallel computing and programming of parallel environmentParallel computing and programming of parallel environment
Parallel computing and programming of parallel environment
areebakanwal12
 
Web Engineering Process Models- An introduction.pptx
Web Engineering Process Models- An introduction.pptxWeb Engineering Process Models- An introduction.pptx
Web Engineering Process Models- An introduction.pptx
areebakanwal12
 
professional ethics about ethical values in workplace
professional ethics about ethical values in workplaceprofessional ethics about ethical values in workplace
professional ethics about ethical values in workplace
areebakanwal12
 
turing machine theory and making process.pptx
turing machine theory and making process.pptxturing machine theory and making process.pptx
turing machine theory and making process.pptx
areebakanwal12
 
Classes and objects object oriented programming
Classes and objects object oriented programmingClasses and objects object oriented programming
Classes and objects object oriented programming
areebakanwal12
 
SE_Requirement Engineering Process Models
SE_Requirement Engineering Process ModelsSE_Requirement Engineering Process Models
SE_Requirement Engineering Process Models
areebakanwal12
 
Data encapsulation and information hiding
Data encapsulation and information hidingData encapsulation and information hiding
Data encapsulation and information hiding
areebakanwal12
 
Ad

Recently uploaded (15)

DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
werhkr1
 
Paper: World Game (s) Great Redesign.pdf
Paper: World Game (s) Great Redesign.pdfPaper: World Game (s) Great Redesign.pdf
Paper: World Game (s) Great Redesign.pdf
Steven McGee
 
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
Taqyea
 
AG-FIRMA Ai Agent for Agriculture | RAG ..
AG-FIRMA Ai Agent for Agriculture  | RAG ..AG-FIRMA Ai Agent for Agriculture  | RAG ..
AG-FIRMA Ai Agent for Agriculture | RAG ..
Anass Nabil
 
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
emestica1
 
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness GuideThe Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
russellpeter1995
 
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdfGiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
Giacomo Vacca
 
introduction to html and cssIntroHTML.ppt
introduction to html and cssIntroHTML.pptintroduction to html and cssIntroHTML.ppt
introduction to html and cssIntroHTML.ppt
SherifElGohary7
 
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
Taqyea
 
ProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptxProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptx
OlenaKotovska
 
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and MonitoringPresentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
mdaoudi
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
IoT PPT introduction to internet of things
IoT PPT introduction to internet of thingsIoT PPT introduction to internet of things
IoT PPT introduction to internet of things
VaishnaviPatil3995
 
Breaking Down the Latest Spectrum Internet Plans.pdf
Breaking Down the Latest Spectrum Internet Plans.pdfBreaking Down the Latest Spectrum Internet Plans.pdf
Breaking Down the Latest Spectrum Internet Plans.pdf
Internet Bundle Now
 
Cloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptxCloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptx
marketing140789
 
DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
DEF CON 25 - Whitney-Merrill-and-Terrell-McSweeny-Tick-Tick-Boom-Tech-and-the...
werhkr1
 
Paper: World Game (s) Great Redesign.pdf
Paper: World Game (s) Great Redesign.pdfPaper: World Game (s) Great Redesign.pdf
Paper: World Game (s) Great Redesign.pdf
Steven McGee
 
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
美国文凭明尼苏达大学莫里斯分校毕业证范本UMM学位证书
Taqyea
 
AG-FIRMA Ai Agent for Agriculture | RAG ..
AG-FIRMA Ai Agent for Agriculture  | RAG ..AG-FIRMA Ai Agent for Agriculture  | RAG ..
AG-FIRMA Ai Agent for Agriculture | RAG ..
Anass Nabil
 
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
CompTIA-Security-Study-Guide-with-over-500-Practice-Test-Questions-Exam-SY0-7...
emestica1
 
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness GuideThe Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
The Hidden Risks of Hiring Hackers to Change Grades: An Awareness Guide
russellpeter1995
 
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdfGiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
GiacomoVacca - WebRTC - troubleshooting media negotiation.pdf
Giacomo Vacca
 
introduction to html and cssIntroHTML.ppt
introduction to html and cssIntroHTML.pptintroduction to html and cssIntroHTML.ppt
introduction to html and cssIntroHTML.ppt
SherifElGohary7
 
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
学生卡英国RCA毕业证皇家艺术学院电子毕业证学历证书
Taqyea
 
ProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptxProjectArtificial Intelligence Good or Evil.pptx
ProjectArtificial Intelligence Good or Evil.pptx
OlenaKotovska
 
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and MonitoringPresentation Mehdi Monitorama 2022 Cancer and Monitoring
Presentation Mehdi Monitorama 2022 Cancer and Monitoring
mdaoudi
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
IoT PPT introduction to internet of things
IoT PPT introduction to internet of thingsIoT PPT introduction to internet of things
IoT PPT introduction to internet of things
VaishnaviPatil3995
 
Breaking Down the Latest Spectrum Internet Plans.pdf
Breaking Down the Latest Spectrum Internet Plans.pdfBreaking Down the Latest Spectrum Internet Plans.pdf
Breaking Down the Latest Spectrum Internet Plans.pdf
Internet Bundle Now
 
Cloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptxCloud-to-cloud Migration presentation.pptx
Cloud-to-cloud Migration presentation.pptx
marketing140789
 
Ad

Classes and objects constructor and destructor

  • 2. Introduction • Object-oriented programming (OOP) – Encapsulation: encapsulates data (attributes) and functions (behavior) into packages called classes – Information hiding : implementation details are hidden within the classes themselves • Classes – Classes are the standard unit of programming – A class is like a blueprint – reusable – Objects are instantiated (created) from the class – For example, a house is an instance of a “blueprint class”
  • 3. Implementing a Time Abstract Data Type with a Class • Classes – Model objects that have attributes (data members) and behaviors (member functions) – Defined using keyword class – Have a body delineated with braces ({ and }) – Class definitions terminate with a semicolon – Example:
  • 4. 1 class Time { 2 public: 3 Time(); 4 void setTime( int, int, int ); 5 void printMilitary(); 6 void printStandard(); 7 private: 8 int hour; // 0 - 23 9 int minute; // 0 - 59 10 int second; // 0 - 59 11 }; Public: and Private: are member-access specifiers. setTime, printMilitary, and printStandard are member functions. Time is the constructor. hour, minute, and second are data members.
  • 5. Implementing a Time Abstract Data Type with a Class • Member access specifiers – Classes can limit the access to their member functions and data – The three types of access a class can grant are: • Public — Accessible wherever the program has access to an object of the class • private — Accessible only to member functions of the class • Protected — Similar to private and discussed later • Constructor – Special member function that initializes the data members of a class object – Cannot return values – Have the same name as the class
  • 6. Objects • Class definition and declaration – Once a class has been defined, it can be used as a type in object, array and pointer declarations – Example: Time sunset, // object of type Time arrayOfTimes[ 5 ], // array of Time objects *pointerToTime, // pointer to a Time object &dinnerTime = sunset; // reference to a Time object Note: The class name becomes the new type specifier.
  • 7. 1 // Fig. 6.3: fig06_03.cpp 2 // Time class. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // Time abstract data type (ADT) definition 9 class Time { 10 public: 11 Time(); // constructor 12 void setTime( int, int, int ); // set hour, minute, second 13 void printMilitary(); // print military time format 14 void printStandard(); // print standard time format 15 private: 16 int hour; // 0 – 23 17 int minute; // 0 – 59 18 int second; // 0 – 59 19 }; 20 21 // Time constructor initializes each data member to zero. 22 // Ensures all Time objects start in a consistent state. 23 Time::Time() { hour = minute = second = 0; } 24 25 // Set a new Time value using military time. Perform validity 26 // checks on the data values. Set invalid values to zero. 27 void Time::setTime( int h, int m, int s ) 28 { 29 hour = ( h >= 0 && h < 24 ) ? h : 0; 30 minute = ( m >= 0 && m < 60 ) ? m : 0; 31 second = ( s >= 0 && s < 60 ) ? s : 0; 32 } Note the :: preceding the function names.
  • 8. 33 34 // Print Time in military format 35 void Time::printMilitary() 36 { 37 cout << ( hour < 10 ? "0" : "" ) << hour << ":" 38 << ( minute < 10 ? "0" : "" ) << minute; 39 } 40 41 // Print Time in standard format 42 void Time::printStandard() 43 { 44 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) 45 << ":" << ( minute < 10 ? "0" : "" ) << minute 46 << ":" << ( second < 10 ? "0" : "" ) << second 47 << ( hour < 12 ? " AM" : " PM" ); 48 } 49 50 // Driver to test simple class Time 51 int main() 52 { 53 Time t; // instantiate object t of class Time 54 55 cout << "The initial military time is "; 56 t.printMilitary(); 57 cout << "nThe initial standard time is "; 58 t.printStandard(); 59
  • 9. 60 t.setTime( 13, 27, 6 ); 61 cout << "nnMilitary time after setTime is "; 62 t.printMilitary(); 63 cout << "nStandard time after setTime is "; 64 t.printStandard(); 65 66 t.setTime( 99, 99, 99 ); // attempt invalid settings 67 cout << "nnAfter attempting invalid settings:" 68 << "nMilitary time: "; 69 t.printMilitary(); 70 cout << "nStandard time: "; 71 t.printStandard(); 72 cout << endl; 73 return 0; 74 } The initial military time is 00:00 The initial standard time is 12:00:00 AM Military time after setTime is 13:27 Standard time after setTime is 1:27:06 PM After attempting invalid settings: Military time: 00:00 Standard time: 12:00:00 AM
  • 10. Implementing a Time ADT with a Class • Destructors – Functions with the same name as the class but preceded with a tilde character (~) – Cannot take arguments and cannot be overloaded – Performs “termination housekeeping” • Binary scope resolution operator (::) – Combines the class name with the member function name – Different classes can have member functions with the same name • Format for defining member functions ReturnType ClassName::MemberFunctionName( ){ … }
  • 11. • If a member function is defined inside the class – Scope resolution operator and class name are not needed – Defining a function outside a class does not change it being public or private • Classes encourage software reuse – Inheritance allows new classes to be derived from old ones Implementing a Time ADT with a Class
  • 12. Class Scope and Accessing Class Members • Class scope – Data members and member functions • File scope – Nonmember functions • Inside a scope – Members accessible by all member functions • Referenced by name • Outside a scope – Members are referenced through handles • An object name, a reference to an object or a pointer to an object
  • 13. Class Scope and Accessing Class Members • Function scope – Variables only known to function they are defined in – Variables are destroyed after function completion • Accessing class members – Same as structs – Dot (.) for objects and arrow (->) for pointers – Example: • t.hour is the hour element of t • TimePtr->hour is the hour element
  • 14. 1 // Fig. 6.4: fig06_04.cpp 2 // Demonstrating the class member access operators . and -> 3 // 4 // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! 5 #include <iostream> 6 7 using std::cout; 8 using std::endl; 9 10 // Simple class Count 11 class Count { 12 public: 13 int x; 14 void print() { cout << x << endl; } 15 }; 16 17 int main() 18 { 19 Count counter, // create counter object 20 *counterPtr = &counter, // pointer to counter 21 &counterRef = counter; // reference to counter 22 23 cout << "Assign 7 to x and print using the object's name: "; 24 counter.x = 7; // assign 7 to data member x 25 counter.print(); // call member function print 26 27 cout << "Assign 8 to x and print using a reference: "; 28 counterRef.x = 8; // assign 8 to data member x 29 counterRef.print(); // call member function print 30
  • 15. 31 cout << "Assign 10 to x and print using a pointer: "; 32 counterPtr->x = 10; // assign 10 to data member x 33 counterPtr->print(); // call member function print 34 return 0; 35 } Assign 7 to x and print using the object's name: 7 Assign 8 to x and print using a reference: 8 Assign 10 to x and print using a pointer: 10
  • 16. Controlling Access to Members • public – Presents clients with a view of the services the class provides (interface) – Data and member functions are accessible • private – Default access mode – Data only accessible to member functions and friends – private members only accessible through the public class interface using public member functions
  • 17. 1 // Fig. 6.6: fig06_06.cpp 2 // Demonstrate errors resulting from attempts 3 // to access private class members. 4 #include <iostream> 5 6 using std::cout; 7 8 #include "time1.h" 9 10 int main() 11 { 12 Time t; 13 14 // Error: 'Time::hour' is not accessible 15 t.hour = 7; 16 17 // Error: 'Time::minute' is not accessible 18 cout << "minute = " << t.minute; 19 20 return 0; 21 } Compiling... Fig06_06.cpp D:Fig06_06.cpp(15) : error C2248: 'hour' : cannot access private member declared in class 'Time' D:Fig6_06time1.h(18) : see declaration of 'hour' D:Fig06_06.cpp(18) : error C2248: 'minute' : cannot access private member declared in class 'Time' D:time1.h(19) : see declaration of 'minute' Error executing cl.exe. test.exe - 2 error(s), 0 warning(s) Attempt to access private member variable minute. Attempt to modify private member variable hour.
  • 18. Class definition class class_name { public: constructor and destructor member functions private: data members };
  • 19. Initializing Class Objects: Constructors • Constructors – Initialize class members – Same name as the class – No return type – Member variables can be initialized by the constructor or set afterwards • Passing arguments to a constructor – When an object of a class is declared, initializers can be provided – Format of declaration with initializers: Class-type ObjectName( value1,value2,…); – Default arguments may also be specified in the constructor prototype
  • 20. 1 // Fig. 6.8: time2.h 2 // Declaration of the Time class. 3 // Member functions are defined in time2.cpp 4 5 // preprocessor directives that 6 // prevent multiple inclusions of header file 7 #ifndef TIME2_H 8 #define TIME2_H 9 10 // Time abstract data type definition 11 class Time { 12 public: 13 Time( int = 0, int = 0, int = 0 ); // default constructor 14 void setTime( int, int, int ); // set hour, minute, second 15 void printMilitary(); // print military time format 16 void printStandard(); // print standard time format 17 private: 18 int hour; // 0 - 23 19 int minute; // 0 - 59 20 int second; // 0 - 59 21 }; 22 23 #endif
  • 21. 61 // Fig. 6.8: fig06_08.cpp 62 // Demonstrating a default constructor 63 // function for class Time. 64 #include <iostream> 65 66 using std::cout; 67 using std::endl; 68 69 #include "time2.h" 70 71 int main() 72 { 73 Time t1, // all arguments defaulted 74 t2(2), // minute and second defaulted 75 t3(21, 34), // second defaulted 76 t4(12, 25, 42), // all values specified 77 t5(27, 74, 99); // all bad values specified 78 79 cout << "Constructed with:n" 80 << "all arguments defaulted:n "; 81 t1.printMilitary(); 82 cout << "n "; 83 t1.printStandard(); 84 85 cout << "nhour specified; minute and second defaulted:" 86 << "n "; 87 t2.printMilitary(); 88 cout << "n "; 89 t2.printStandard(); 90 91 cout << "nhour and minute specified; second defaulted:" 92 << "n "; 93 t3.printMilitary();
  • 22. OUTPUT Constructed with: all arguments defaulted: 00:00 12:00:00 AM hour specified; minute and second defaulted: 02:00 2:00:00 AM hour and minute specified; second defaulted: 21:34 9:34:00 PM hour, minute, and second specified: 12:25 12:25:42 PM all invalid values specified: 00:00 12:00:00 AM When only hour is specified, minute and second are set to their default values of 0. 94 cout << "n "; 95 t3.printStandard(); 96 97 cout << "nhour, minute, and second specified:" 98 << "n "; 99 t4.printMilitary(); 100 cout << "n "; 101 t4.printStandard(); 102 103 cout << "nall invalid values specified:" 104 << "n "; 105 t5.printMilitary(); 106 cout << "n "; 107 t5.printStandard(); 108 cout << endl; 109 110 return 0; 111 }
  • 23. Using Destructors • Destructors – Are member function of class – Perform termination housekeeping before the system reclaims the object’s memory – Complement of the constructor – Name is tilde (~) followed by the class name (i.e., ~Time) • Recall that the constructor’s name is the class name – Receives no parameters, returns no value – One destructor per class • No overloading allowed
  • 24. When Constructors and Destructors Are Called • Constructors and destructors called automatically – Order depends on scope of objects • Global scope objects – Constructors called before any other function (including main) – Destructors called when main terminates (or exit function called) – Destructors not called if program terminates with abort • Automatic local objects – Constructors called when objects are defined – Destructors called when objects leave scope • i.e., when the block in which they are defined is exited – Destructors not called if the program ends with exit or abort
  • 25. • Static local objects – Constructors called when execution reaches the point where the objects are defined – Destructors called when main terminates or the exit function is called – Destructors not called if the program ends with abort When Constructors and Destructors Are Called
  翻译: