Post on 09-Oct-2020
Fall 2014
Instructor: Reza Entezari-Maleki
Email: entezari@ce.sharif.edu
Sharif University of Technology 1
Fundamentals of Programming Session 27
These slides have been created using Deitel’s slides
Outlines
Constructors
Destructors
When Constructors and Destructors Are Called
Default Memberwise Assignment
Union
Introducing enum
File Processing
Data Hierarchy
Files and Streams
Creating a Sequential-Access File
2
Constructors
Initialize data members
Or can set later
Same name as class
No return type
Initializers
Passed as arguments to constructor
In parentheses to right of class name before semicolon
Class-type ObjectName( value1,value2,…);
3
Constructors
4
1 // Member functions for class SalesPerson.
2 #include <iostream>
3 #include <iomanip>
4 using namespace std;
5 // class definition
6 class SalesPerson {
7 public:
8 SalesPerson(); // constructor
9 void getSalesFromUser(); // input sales from keyboard
10 void setSales( int, double ); // set sales for a month
11 void printAnnualSales(); // summarize and print sales
12 private:
13 double totalAnnualSales(); // utility function
14 double sales[ 12 ]; // 12 monthly sales figures
15 }; // end class SalesPerson
5
16 SalesPerson::SalesPerson()
17 {
18 for ( int i = 0; i < 12; i++ )
19 sales[ i ] = 0.0;
20 } // end SalesPerson constructor
21 // get 12 sales figures from the user at the keyboard
22 void SalesPerson::getSalesFromUser()
23 {
24 double salesFigure;
25 for ( int i = 1; i <= 12; i++ ) {
26 cout << "Enter sales amount for month " << i << ": ";
27 cin >> salesFigure;
28 setSales( i, salesFigure );
29 } // end for
30 } // end function getSalesFromUser
31 // set one of the 12 monthly sales figures; function subtracts
32 // one from month value for proper subscript in sales array
6
33 void SalesPerson::setSales( int month, double amount )
34 {
35 // test for valid month and amount values
36 if ( month >= 1 && month <= 12 && amount > 0 )
37 sales[ month - 1 ] = amount; // adjust for subscripts 0-11
38 else // invalid month or amount value
39 cout << "Invalid month or sales figure" << endl;
40 } // end function setSales
41 // print total annual sales (with help of utility function)
42 void SalesPerson::printAnnualSales()
43 {
44 cout << setprecision( 2 ) << fixed
45 << "\nThe total annual sales are: $"
46 << totalAnnualSales() << endl; // call utility function
47 } // end function printAnnualSales
48 // private utility function to total annual sales
7
49 double SalesPerson::totalAnnualSales()
50 {
51 double total = 0.0; // initialize total
52 for ( int i = 0; i < 12; i++ ) // summarize sales results
53 total += sales[ i ];
54 return total;
55 } // end function totalAnnualSales
56 int main()
57 {
58 SalesPerson s; // create SalesPerson object s
59 s.getSalesFromUser(); // note simple sequential code; no
60 s.printAnnualSales(); // control structures in main
61 return 0;
62 } // end main
8
Enter sales amount for month 1: 5314.76
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
Constructors
Can specify default arguments
Default constructors
Defaults all arguments
OR
Explicitly requires no arguments
Can be invoked with no arguments
Only one per class
9
Constructors …
10
1 #include <iostream>
2 #include <iomanip>
3 using namespace std;
4
5 classTime {
6 public:
7 Time( int = 0, int = 0, int = 0); // default constructor
8 void setTime( int, int, int ); // set hour, minute, second
9 void printUniversal(); // print universal-time format
10 void printStandard(); // print standard-time format
11 private:
12 int hour; // 0 - 23 (24-hour clock format)
13 int minute; // 0 - 59
14 int second; // 0 - 59
15 }; // end class Time
11
// ensures all Time objects start in a consistent state
16 Time::Time( int hr, int min, int sec )
17 {
18 setTime( hr, min, sec ); // validate and set time
19 } // end Time constructor
20 // set new Time value using universal time, perform validity
21 // checks on the data values and set invalid values to zero
22 voidTime::setTime( int h, int m, int s )
23 {
24 hour = ( h >= 0 && h < 24 ) ? h : 0;
25 minute = ( m >= 0 && m < 60 ) ? m : 0;
26 second = ( s >= 0 && s < 60 ) ? s : 0;
27 } // end function setTime
28 // print Time in universal format
29 voidTime::printUniversal()
30 {
31 cout << setfill( '0' ) << setw( 2 ) << hour << ":"
32 << setw( 2 ) << minute << ":"
33 << setw( 2 ) << second;
34 } // end function printUniversal
12
30 // print Time in standard format
31 voidTime::printStandard()
32 {
33 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
34 << ":" << setfill( '0' ) << setw( 2 ) << minute
35 << ":" << setw( 2 ) << second
36 << ( hour < 12 ? " AM" : " PM" );
37
38 } // end function printStandard
13
7 int main()
8 {
9 Time t1; // all arguments defaulted
10 Time t2( 2 ); // minute and second defaulted
11 Time t3( 21, 34 ); // second defaulted
12 Time t4( 12, 25, 42 ); // all values specified
13 Time t5( 27, 74, 99 ); // all bad values specified
14 cout << "Constructed with:\n\n"
15 << "all default arguments:\n ";
16 t1.printUniversal(); // 00:00:00
17 cout << "\n ";
18 t1.printStandard(); // 12:00:00 AM
14
19 cout << "\n\nhour specified; default minute and second:\n ";
20 t2.printUniversal(); // 02:00:00
21 cout << "\n ";
22 t2.printStandard(); // 2:00:00 AM
23 cout << "\n\nhour and minute specified; default second:\n ";
24 t3.printUniversal(); // 21:34:00
25 cout << "\n ";
26 t3.printStandard(); // 9:34:00 PM
27 cout << "\n\nhour, minute, and second specified:\n ";
28 t4.printUniversal(); // 12:25:42
29 cout << "\n ";
30 t4.printStandard(); // 12:25:42 PM
31 cout << "\n\nall invalid values specified:\n ";
32 t5.printUniversal(); // 00:00:00
33 cout << "\n ";
34 t5.printStandard(); // 12:00:00 AM
35 cout << endl;
36 return 0;
37 } // end main
15
Constructed with:
all default arguments:
00:00:00
12:00:00 AM
hour specified; default minute and second:
02:00:00
2:00:00 AM
hour and minute specified; default second:
21:34:00
9:34:00 PM
hour, minute, and second specified:
12:25:42
12:25:42 PM
all invalid values specified:
00:00:00
12:00:00 AM
Destructors
Special member function
Same name as class
Preceded with tilde (~)
No arguments
No return value
Cannot be overloaded
No explicit destructor
Compiler creates “empty” destructor
16
Destructors
Constructors and destructors
Called implicitly by compiler
Order of function calls
Depends on order of execution
When execution enters and exits scope of objects
Generally, destructor calls reverse order of constructor calls
17
Destructors …
Order of constructor, destructor function calls
Global scope objects Constructors
Before any other function (including main)
Destructors
When main terminates (or exit function called)
Not called if program terminates with abort
Automatic local objects Constructors
When objects defined
o Each time execution enters scope
Destructors
When objects leave scope
o Execution exits block in which object defined
Not called if program ends with exit or abort18
When Constructors and Destructors Are Called
Order of constructor, destructor function calls
static local objects
Constructors
Exactly once
When execution reaches point where object defined
Destructors
When main terminates or exit function called
Not called if program ends with abort
19
When Constructors and Destructors Are Called …
20
1 #include <iostream>
2 using namespace std;
3 // Definition of class CreateAndDestroy.
4 class CreateAndDestroy {
5 public:
6 CreateAndDestroy( int, char * ); // constructor
7 ~CreateAndDestroy(); // destructor
8 private:
9 int objectID;
10 char *message;
11 }; // end class CreateAndDestroy
12 // constructor
13 CreateAndDestroy::CreateAndDestroy(
14 int objectNumber, char *messagePtr )
15 {
16 objectID = objectNumber;
17 message = messagePtr;
18 cout << "Object " << objectID << " constructor runs "
19 << message << endl;
20 } // end CreateAndDestroy constructor
21
21 // destructor
22 CreateAndDestroy::~CreateAndDestroy()
23 {
24 // the following line is for pedagogic purposes only
25 cout << ( objectID == 1 || objectID == 6 ? "\n" : "" );
26
27 cout << "Object " << objectID << " destructor runs "
28 << message << endl;
29
30 } // end ~CreateAndDestroy destructor
31
32 void create( void ); // prototype
33 // global object
34 CreateAndDestroy first( 1, "(global before main)" );
35 int main()
36 {
37 cout << "\nMAIN FUNCTION: EXECUTION BEGINS" << endl;
38 CreateAndDestroy second( 2, "(local automatic in main)" );
39 static CreateAndDestroy third(
40 3, "(local static in main)" );
22
41 create(); // call function to create objects
42 cout << "\nMAIN FUNCTION: EXECUTION RESUMES" << endl;
43 CreateAndDestroy fourth( 4, "(local automatic in main)" );
44 cout << "\nMAIN FUNCTION: EXECUTION ENDS" << endl;
45 return 0;
46 } // end main
47 // function to create objects
48 void create( void )
49 {
50 cout << "\nCREATE FUNCTION: EXECUTION BEGINS" << endl;
51 CreateAndDestroy fifth( 5, "(local automatic in create)" );
52 static CreateAndDestroy sixth(
53 6, "(local static in create)" );
54 CreateAndDestroy seventh(
55 7, "(local automatic in create)" );
56 cout << "\nCREATE FUNCTION: EXECUTION ENDS\" << endl;
57 } // end function create
23
Object 1 constructor runs (global before main)
MAIN FUNCTION: EXECUTION BEGINS
Object 2 constructor runs (local automatic in main)
Object 3 constructor runs (local static in main)
CREATE FUNCTION: EXECUTION BEGINS
Object 5 constructor runs (local automatic in create)
Object 6 constructor runs (local static in create)
Object 7 constructor runs (local automatic in create)
CREATE FUNCTION: EXECUTION ENDS
Object 7 destructor runs (local automatic in create)
Object 5 destructor runs (local automatic in create)
MAIN FUNCTION: EXECUTION RESUMES
Object 4 constructor runs (local automatic in main)
MAIN FUNCTION: EXECUTION ENDS
Object 4 destructor runs (local automatic in main)
Object 2 destructor runs (local automatic in main)
Object 6 destructor runs (local static in create)
Object 3 destructor runs (local static in main)
Object 1 destructor runs (global before main)
Assigning objects
Assignment operator (=)
Can assign one object to another of same type
Default: memberwise assignment
Each right member assigned individually to left member
Passing, returning objects
Objects passed as function arguments
Objects returned from functions
Default: pass-by-value
Copy of object passed, returned
Copy constructor
o Copy original values into new object24
Default Memberwise Assignment
25
1 // Demonstrating that class objects can be assigned
2 // to each other using default memberwise assignment.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 // class Date definition
7 class Date {
8 public:
9 Date( int = 1, int = 1, int = 1990 ); // default constructor
10 void print();
11 private:
12 int month;
13 int day;
14 int year;
15 }; // end class Date
26
16 // Date constructor with no range checking
17 Date::Date( int m, int d, int y )
18 {
19 month = m;
20 day = d;
21 year = y;
22 } // end Date constructor
23 // print Date in the format mm-dd-yyyy
24 void Date::print()
25 {
26 cout << month << '-' << day << '-' << year;
27 } // end function print
28 int main()
29 {
30 Date date1( 7, 4, 2002 );
31 Date date2; // date2 defaults to 1/1/1990
27
32 cout << "date1 = ";
33 date1.print();
34 cout << "\ndate2 = ";
35 date2.print();
36 date2 = date1; // default memberwise assignment
37 cout << "\n\nAfter default memberwise assignment, date2 = ";
38 date2.print();
39 cout << endl;
40 return 0;
41 } // end main
date1 = 7-4-2002
date2 = 1-1-1990
After default memberwise assignment, date2 = 7-4-2002
Union
Memory that contains a variety of objects
Data members share space
Only contains one data member at a time
Only the last data member defined can be accessed
Declaration same as class or structunion Number {
int x;
float y;
};
Numebr myObject;
28
Union
29
1 // Fig. 20.8: fig20_08.cpp
2 // An example of a union.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 // define union Number
7 union Number {
8 int integer1;
9 double double1;
10 }; // end union Number
11 int main()
12 {
13 Number value; // union variable
14 value.integer1 = 100; // assign 100 to member integer1
15 cout << "Put a value in the integer member\n"
16 << "and print both members.\nint: "
17 << value.integer1 << "\ndouble: " << value.double1
18 << endl;
30
19 value.double1 = 100.0; // assign 100.0 to member double1
20 cout << "Put a value in the floating member\n"
21 << "and print both members.\nint: "
22 << value.integer1 << "\ndouble: " << value.double1
23 << endl;
24 return 0;
25 } // end main
Put a value in the integer member
and print both members.
int: 100
double: -9.25596e+061
Put a value in the floating member
and print both members.
int: 0
double: 100
31
1 // Fig. 20.9: fig20_09.cpp
2 // Using an anonymous union.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 int main()
7 {
8 // declare an anonymous union
9 // members integer1, double1 and charPtr share the same space
10 union {
11 int integer1;
12 double double1;
13 char *charPtr;
14 }; // end anonymous union
15 // declare local variables
16 int integer2 = 1;
17 double double2 = 3.3;
18 char *char2Ptr = "Anonymous";
32
19 // assign value to each union member
20 // successively and print each
21 cout << integer2 << ' ';
22 integer1 = 2;
23 cout << integer1 << endl;
24
25 cout << double2 << ' ';
26 double1 = 4.4;
27 cout << double1 << endl;
28
29 cout << char2Ptr << ' ';
30 charPtr = "union";
31 cout << charPtr << endl;
32 return 0;
33 } // end main
1 2
3.3 4.4
Anonymous union
Enumeration
Set of integers with identifiers
enum typeName {constant1, constant2…};
Constants start at 0 (default), incremented by 1
Constants need unique names
Cannot assign integer to enumeration variable
Must use a previously defined enumeration type
Exampleenum Status {CONTINUE, WON, LOST};
Status enumVar;
enumVar = WON; // cannot do enumVar = 1
33
Introducing enum
Enumeration constants can have preset values
enum Months { JAN = 1, FEB, MAR, APR,
MAY, JUN, JUL, AUG, SEP, OCT, NOV,
DEC};
Starts at 1, increments by 1
Next: craps simulator
Roll two dice
7 or 11 on first throw: player wins
2, 3, or 12 on first throw: player loses
4, 5, 6, 8, 9, 10
Value becomes player's "point"
Player must roll his point before rolling 7 to win34
Introducing enum …
35
1 // Fig. 3.10: fig03_10.cpp
2 // Craps.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 // contains function prototypes for functions srand and rand
7 #include <cstdlib>
8 #include <ctime> // contains prototype for function time
9 int rollDice( void ); // function prototype
10 int main()
11 {
12 // enumeration constants represent game status
13 enum Status { CONTINUE, WON, LOST };
14 int sum;
15 int myPoint;
16 Status gameStatus; // can contain CONTINUE, WON or LOST
36
17 // randomize random number generator using current time
18 srand( time( 0 ) );
19 sum = rollDice(); // first roll of the dice
20 // determine game status and point based on sum of dice
21 switch ( sum ) {
22 // win on first roll
23 case 7:
24 case 11:
25 gameStatus = WON;
26 break;
27 // lose on first roll
28 case 2:
29 case 3:
30 case 12:
31 gameStatus = LOST;
32 break;
37
33 // remember point
34 default:
35 gameStatus = CONTINUE;
36 myPoint = sum;
37 cout << "Point is " << myPoint << endl;
38 break; // optional
39 } // end switch
40 // while game not complete ...
41 while ( gameStatus == CONTINUE ) {
42 sum = rollDice(); // roll dice again
43 // determine game status
44 if ( sum == myPoint ) // win by making point
45 gameStatus = WON;
46 else
47 if ( sum == 7 ) // lose by rolling 7
48 gameStatus = LOST;
49 } // end while
38
50 // display won or lost message
51 if ( gameStatus == WON )
52 cout << "Player wins" << endl;
53 else
54 cout << "Player loses" << endl;
55 return 0; // indicates successful termination
56 } // end main
57 // roll dice, calculate sum and display results
58 int rollDice( void )
59 {
60 int die1;
61 int die2;
62 int workSum;
63 die1 = 1 + rand() % 6; // pick random die1 value
64 die2 = 1 + rand() % 6; // pick random die2 value
65 workSum = die1 + die2; // sum die1 and die2
39
66 // display results of this roll
67 cout << "Player rolled " << die1 << " + " << die2
68 << " = " << workSum << endl;
69 return workSum; // return sum of dice
70 } // end function rollDice
Player rolled 2 + 5 = 7
Player wins
Player rolled 6 + 6 = 12
Player loses
Player rolled 3 + 3 = 6
Point is 6
Player rolled 5 + 3 = 8
Player rolled 4 + 5 = 9
Player rolled 2 + 1 = 3
Player rolled 1 + 5 = 6
Player wins
40
Player rolled 1 + 3 = 4
Point is 4
Player rolled 4 + 6 = 10
Player rolled 2 + 4 = 6
Player rolled 6 + 4 = 10
Player rolled 2 + 3 = 5
Player rolled 2 + 4 = 6
Player rolled 1 + 1 = 2
Player rolled 4 + 4 = 8
Player rolled 4 + 3 = 7
Player loses
Storage of data
Arrays, variables are temporary
Files are permanent
Magnetic disk, optical disk, tapes
41
File Processing
From smallest to largest
Bit (binary digit)
1 or 0
Everything in computer ultimately represented as bits
Cumbersome for humans to use
Character set
Digits, letters, symbols used to represent data
Every character represented by 1's and 0's
Byte: 8 bits
Can store a character (char)
42
Data Hierarchy
From smallest to largest (continued)
Field: group of characters with some meaning
Your name
Record: group of related fields
struct or class in C++
Each field associated with same employee
Record key: field used to uniquely identify record
File: group of related records
Sequential file: records stored by key
Database: group of related files
43
Data Hierarchy …
44
Data Hierarchy …
1
01001010
Judy
Judy Green
Sally Black
Tom Blue
Judy Green
Iris Orange
Randy Red
File
Record
Field
Byte (ASCII character J)
Bit
C++ views file as sequence of bytes
Ends with end-of-file marker
When file opened
Object created, stream associated with it
cin, cout, etc. created when <iostream> included
Communication between program and file/device
45
Files and Streams
0 31 2 4 5 8 9
...
... n-1
end-of-file marker
6 7
C++ imposes no structure on file
Concept of "record" must be implemented by programmer
To open file, create objects
Classes
ifstream (input only)
ofstream (output only)
fstream (I/O)
Constructors take file name and file-open modeofstream outClientFile( "filename", fileOpenMode );
To attach a file laterOfstream outClientFile;
outClientFile.open( "filename", fileOpenMode);
46
Creating a Sequential-Access File
File-open modes
ofstream opened for output by default ofstream outClientFile( "clients.dat", ios::out );
ofstream outClientFile( "clients.dat");
47
Creating a Sequential-Access File …
Mode Description
ios::app Write all output to the end of the file.
ios::in Open a file for input.
ios::out Open a file for output.
ios::binary Open a file for binary (i.e., non-text) input or
output.
Operations
Overloaded operator!
!outClientFile
Returns nonzero (true) if badbit or failbit set
Opened non-existent file for reading, wrong permissions
Operations
Writing to file (just like cout)
outClientFile << myVariable
Closing file
outClientFile.close()
Automatically closed when destructor called
48
Creating a Sequential-Access File …