File 1725109964 5000741 OBJECTSASMEMBERSOFCLASS
File 1725109964 5000741 OBJECTSASMEMBERSOFCLASS
Program Output
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:
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.
Time is the constructor.
8 int hour; // 0 - 23
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
• 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:
34 return 0;
35 }
Compiling...
Fig06_06.cpp
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.
• Following example
– Program to take in monthly sales and output the total
– Implementation not shown, only access functions
87 // Fig. 6.7: fig06_07.cpp
88 // Demonstrating a utility function
89 // Compile with salesp.cpp
90 #include "salesp.h"
Create object s, an instance
91
of class SalesPerson
92 int main()
93 {
94 SalesPerson s; // create SalesPerson object s
95
96 s.getSalesFromUser(); // note simple sequential code
97 s.printAnnualSales(); // no control structures in main
98 return 0;
99 }
OUTPUT
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
18 #include <iostream>
19
20 using std::cout;
21 using std::endl;
22
23 #include "create.h"
24
29 }
30
31 CreateAndDestroy::~CreateAndDestroy()
32 { cout << "Object " << data << " destructor " << endl; }
33 // Fig. 6.9: fig06_09.cpp
34 // Demonstrating the order in which constructors and
35 // destructors are called.
36 #include <iostream>
37
38 using std::cout;
39 using std::endl;
40
41 #include "create.h"
42
43 void create( void ); // prototype
44
45 CreateAndDestroy first( 1 ); // global object
46
47 int main()
48 {
49 cout << " (global created before main)" << endl;
50
51 CreateAndDestroy second( 2 ); // local object
52 cout << " (local automatic in main)" << endl;
53
54 static CreateAndDestroy third( 3 ); // local object
55 cout << " (local static in main)" << endl;
56
57 create(); // call function to create objects
58
59 CreateAndDestroy fourth( 4 ); // local object
60 cout << " (local automatic in main)" << endl;
61 return 0;
62 }
63
64 // Function to create objects
65 void create( void )
66 {
67 CreateAndDestroy fifth( 5 );
68 cout << " (local automatic in create)" << endl;
69
70 static CreateAndDestroy sixth( 6 );
71 cout << " (local static in create)" << endl;
72
73 CreateAndDestroy seventh( 7 );
74 cout << " (local automatic in create)" << endl;
75 }
OUTPUT
Object 1 constructor (global created before main)
Object 2 constructor (local automatic in main)
Object 3 constructor (local static in main)
Object 5 constructor (local automatic in create)
Object 6 constructor (local static in create)
Object 7 constructor (local automatic in create)
Object 7 destructor
Object 5 destructor Notice how the order of the
Object 4 constructor (local automatic in main)
Object 4 destructor constructor and destructor call
Object 2 destructor depends on the types of variables
Object 6 destructor (automatic, global and static)
Object 3 destructor
Object 1 destructor they are associated with.
Using Data Members and Member
Functions
• Member functions
– Allow clients of the class to set (i.e., write) or get (i.e., read)
the values of private data members
– Example:
Adjusting a customer’s bank balance
• private data member balance of a class BankAccount
could be modified through the use of member function
computeInterest
• A member function that sets data member interestRate could
be called setInterestRate, and a member function that returns
the interestRate could be called getInterestRate
– Providing set and get functions does not make private
variables public
– A set function should ensure that the new value is valid
A Subtle Trap: Returning a Reference to
a Private Data Member
• Reference to an object
– Alias for the name of the object
– May be used on the left side of an assignment statement
– Reference can receive a value, which changes the
original object as well
• Returning references
– public member functions can return non-const
references to private data members
• Should be avoided, breaks encapsulation
1 // Fig. 6.11: time4.h
2 // Declaration of the Time class.
3 // Member functions defined in time4.cpp
4
5 // preprocessor directives that
6 // prevent multiple inclusions of header file
7 #ifndef TIME4_H
8 #define TIME4_H
Notice how member function
9 badSetHour returns a reference
10 class Time { (int & is the return type).
11 public:
12 Time( int = 0, int = 0, int = 0 );
13 void setTime( int, int, int );
14 int getHour();
15 int &badSetHour( int ); // DANGEROUS reference return
16 private:
17 int hour;
18 int minute;
19 int second;
20 };
21
22 #endif
23 // Fig. 6.11: time4.cpp
24 // Member function definitions for Time class.
25 #include "time4.h"
26
27 // Constructor function to initialize private data.
28 // Calls member function setTime to set variables.
29 // Default values are 0 (see class definition).
30 Time::Time( int hr, int min, int sec )
31 { setTime( hr, min, sec ); }
32
33 // Set the values of hour, minute, and second.
34 void Time::setTime( int h, int m, int s )
35 {
36 hour = ( h >= 0 && h < 24 ) ? h : 0;
37 minute = ( m >= 0 && m < 60 ) ? m : 0;
38 second = ( s >= 0 && s < 60 ) ? s : 0;
39 }
40
41
42
// Get the hour value 1. Load header
int Time::getHour() { return hour; }
badSetHour returns a
43
44 // POOR PROGRAMMING PRACTICE:
reference to the private
member variable hour.
45
1.1 Function definitions
// Returning a reference to a private data member.
46 int &Time::badSetHour( int hh ) Changing this reference
47 { will alter hour as well.
48 hour = ( hh >= 0 && hh < 24 ) ? hh : 0;
49
50 return hour; // DANGEROUS reference return
51 }
52 // Fig. 6.11: fig06_11.cpp
53 // Demonstrating a public member function that
54 // returns a reference to a private data member.
55 // Time class has been trimmed for this example.
56 #include <iostream>
57
58 using std::cout;
59 using std::endl;
60
61 #include "time4.h"
62
63 int main()
64 {
65 Time t;
66 int &hourRef = t.badSetHour( 20 );
67
68 cout << "Hour before modification: " << hourRef;
69 hourRef = 30; // modification with invalid value
70 cout << "\nHour after modification: " << t.getHour();
71
72 // Dangerous: Function call that returns Hour after modification: 30
73 // a reference can be used as an lvalue!
74 t.badSetHour(12) = 74;
75 cout << "\n\n*********************************\n"
76 << "POOR PROGRAMMING PRACTICE!!!!!!!!\n"
77 << "badSetHour as an lvalue, Hour: "
78 << t.getHour()
79 << "\n*********************************" << endl;
*********************************
80
81 return 0; POOR PROGRAMMING PRACTICE!!!!!!!!
82 } badSetHour as an lvalue, Hour: 74
*********************************
Hour before modification: 20
Hour after modification: 30
*********************************
POOR PROGRAMMING PRACTICE!!!!!!!!
badSetHour as an lvalue, Hour: 74
*********************************
Program Output
Assignment by Default Memberwise
Copy
• Assigning objects
– An object can be assigned to another object of
the same type using the assignment operator (=)
– Member by member copy
• Objects may be
– Passed as function arguments
– Returned from functions (call-by-value default)
1 // Fig. 6.12: fig06_12.cpp
2 // Demonstrating that class objects can be assigned
3 // to each other using default memberwise copy
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 // Simple Date class
10 class Date {
11 public:
12 Date( int = 1, int = 1, int = 1990 ); // default constructor
13 void print();
14 private:
15 int month;
16 int day;
17 int year;
18 };
19
20 // Simple Date constructor with no range checking
21 Date::Date( int m, int d, int y )
22 {
23 month = m;
24 day = d;
25 year = y;
26 }
27
28 // Print the Date in the form mm-dd-yyyy
29 void Date::print()
30 { cout << month << '-' << day << '-' << year; }
31
32 int main()
33 {
34 Date date1( 7, 4, 1993 ), date2; // d2 defaults to 1/1/90
35
36 cout << "date1 = ";
37 date1.print();
38 cout << "\ndate2 = ";
39 date2.print();
40
41 date2 = date1; // assignment by default memberwise copy
42 cout << "\n\nAfter default memberwise copy, date2 = ";
43 date2.print();
44 cout << endl;
45
46 return 0;
47 }
date1 = 7-4-1993
date2 = 1-1-1990