Constructors and Destructors Presentation
Constructors and Destructors Presentation
Programming
LECTURE 3
Introduction
Information hiding
Implementation details are hidden within the classes themselves
1 class Time {
2 public:
Public: and Private: are
3 Time(); member-access specifiers.
4 void setTime( int, int, int );
5 void printMilitary(); setTime, printMilitary, and
6 void printStandard(); printStandard are member
7 private: functions.
8 int hour; // 0 - 23
Time is the constructor.
9 int minute; // 0 - 59
10 int second; // 0 - 59
hour, minute, and
11 };
second are data
members.
Implementing a Time Abstract Data Type
with a Class (II)
Format
Body delineated with braces ({ and })
Class definition terminates with a semicolon
In following program
Time constructor initializes the data members to 0
Ensures that the object is in a consistent state when it is created
1 // Fig. 16.2: fig16_02.cpp
2 // Time class. Outline
3 #include <iostream>
4
5 using std::cout;
6 using std::endl; 1. Class definition
7
8 // Time abstract data type (ADT) definition
9 class Time {
1.1 Define default values
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 }
33
34 // Print Time in military format Outline
35 void Time::printMilitary()
36 {
37 cout << ( hour < 10 ? "0" : "" ) << hour << ":"
38 << ( minute < 10 ? "0" : "" ) << minute; 1.2 Define the two
39 } functions
40 printMilitary and
41 // Print Time in standard format printstandard
42 void Time::printStandard()
43 { 2. In main(), create an
44 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) object of class Time.
45 << ":" << ( minute < 10 ? "0" : "" ) << minute
46 << ":" << ( second < 10 ? "0" : "" ) << second 2.1 Print the initial
47 << ( hour < 12 ? " AM" : " PM" ); (default) time
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 << "\n\nMilitary time after setTime is "; Outline
62 t.printMilitary();
63 cout << "\nStandard time after setTime is ";
64 t.printStandard();
65 2.2 Set and print the
66 t.setTime( 99, 99, 99 ); // attempt invalid settings time.
67 cout << "\n\nAfter attempting invalid settings:"
68 << "\nMilitary time: "; 2.3 Attempt to set the
69 t.printMilitary(); time to an invalid hour
70 cout << "\nStandard time: ";
71 t.printStandard(); 2.4 Print
72 cout << endl;
73 return 0;
74 }
Class scope
Data members and member functions
File scope
Nonmember functions
Function scope
Variables defined in member functions, destroyed after function
completes
Inside a scope
Members accessible by all member functions
Referenced by name
Class Scope and Accessing Class Members
(II)
Outside a scope
Use handles
An object name, a reference to an object or a pointer to an object
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. 16.3: fig16_03.cpp
2 // Demonstrating the class member access operators . and -> Outline
3 //
4 // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA!
5 #include <iostream>
6 1. Class definition
7 using std::cout;
8 using std::endl; 1.1 Initialize object
9
10 // Simple class Count 2. Print using the dot
11 class Count { operator
12 public:
13 int x;
2.2 Set new value
14 void print() { cout << x << endl; }
15 };
2.3 Print using a
16
17 int main()
reference
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: ";
Purpose of public
Give clients a view of the services the class provides (interface)
Purpose of private
Default setting
Hide details of how the class accomplishes its tasks (implementation)
Private members only accessible through the public interface using
public member functions
1 // Fig. 16.5: fig16_05.cpp
2 // Demonstrate errors resulting from attempts Outline
3 // to access private class members.
4 #include <iostream>
5 1. Load header file for
6 using std::cout;
Time class.
7
8 #include "time1.h"
9 2. Create an object of
10 int main() class Time.
11 {
12 Time t; 2.1 Attempt to set a
13
14 // Error: 'Time::hour' is not accessible
private variable
15 t.hour = 7;
16 2.2 Attempt to access a
17 // Error: 'Time::minute' is not accessible private variable.
18 cout << "minute = " << t.minute;
19
20 return 0;
21 }
Compiling...
Fig06_06.cpp Program Output
D:\Fig06_06.cpp(15) : error C2248: 'hour' : cannot access private
member declared in class 'Time'
D:\Fig6_06\time1.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)
Access Functions and Utility Functions
Utility functions
private functions that support the operation of public functions
Not intended to be used directly by clients
Access functions
public functions that read/display data or check conditions
For a container, it could call the isEmpty function
Next
Program to take in monthly sales and output the total
Implementation not shown, only access functions
87 // Fig. 16.6: fig16_06.cpp
88 // Demonstrating a utility function Outline
89 // Compile with salesp.cpp
90 #include "salesp.h"
91
92 int main() 1. Load header file
93 { (compile with file that
94 SalesPerson s; // create SalesPerson object s contains function
95 definitions)
96 s.getSalesFromUser(); // note simple sequential code
97 s.printAnnualSales(); // no control structures in main 1.1 Create an object
98 return 0;
99 } 2. Function calls
OUTPUT
Enter sales amount for month 1: 5314.76 Program Output
Enter sales amount for month 2: 4292.38
Enter sales amount for month 3: 4589.83
Enter sales amount for month 4: 5534.03
Enter sales amount for month 5: 4376.34
Enter sales amount for month 6: 5698.45
Enter sales amount for month 7: 4439.22
Enter sales amount for month 8: 5893.57
Enter sales amount for month 9: 4909.67
Enter sales amount for month 10: 5123.45
Enter sales amount for month 11: 4024.97
Enter sales amount for month 12: 5923.92
The total annual sales are: $60120.59
Initializing Class Objects: Constructors
Constructor function
Can initialize class members
Same name as the class, no return type
Member variables can be initialized by the constructor or set afterwards
Declaring objects
Initializers can be provided
Initializers passed as arguments to the class’ constructor
Constructors
A Member function with the same name as its classis
called Constructor and it is used to initilize the
objects of that class type with a legal value.
A Constructor is a special member function of a class
that is called automatically when an object of class
is created.
Example :
class Student
{
int rollno;
float marks;
public:
student( ) //Constructor
// Implicit Call
{ Student ob1;
rollno=0;
marks=0.0; // Explicit Call
} Student ob1=student();
//other public members
};
TYPES OF CONSRUCTORS
Example :
class TEST
{ int Regno,Max,Min,Score;
Public:
TEST( ) // Default Constructor
{}
TEST (int Pregno,int Pscore) // Parameterized Constructor
{
Regno = Pregno ;Max=100;Max=100;Min=40;Score=Pscore;
}
~ TEST ( ) // Destructor
{ Cout<<”TEST Over”<<endl;}
};
The following points apply to constructors and
destructors: