0% found this document useful (0 votes)
6 views48 pages

Classes and Data Abstraction in OOP

The document outlines the principles of classes and data abstraction in object-oriented programming, focusing on structures and classes, their definitions, and member access. It discusses the implementation of a Time abstract data type using both structs and classes, emphasizing constructors, destructors, and member functions. Additionally, it covers class scope, access control, and the importance of information hiding and software reusability.

Uploaded by

radaideh7484
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views48 pages

Classes and Data Abstraction in OOP

The document outlines the principles of classes and data abstraction in object-oriented programming, focusing on structures and classes, their definitions, and member access. It discusses the implementation of a Time abstract data type using both structs and classes, emphasizing constructors, destructors, and member functions. Additionally, it covers class scope, access control, and the importance of information hiding and software reusability.

Uploaded by

radaideh7484
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Classes and

Data Abstraction
Outline
Introduction
Structure Definitions
Accessing Members of Structures
Implementing a User-Defined Type Time with a Struct
Implementing a Time Abstract Data Type with a Class
Class Scope and Accessing Class Members
Separating Interface from Implementation
Controlling Access to Members
Access Functions and Utility Functions
Initializing Class Objects: Constructors
Using Default Arguments with Constructors
Using Destructors
When Constructors and Destructors Are Called
Using Data Members and Member Functions
A Subtle Trap: Returning a Reference to a Private Data Member
Assignment by Default Memberwise Copy
Software Reusability

© 2000 Deitel & Associates, Inc. All rights reserved.


Introduction

• Object- oriented programming (OOP)


– encapsulates data (attributes) and functions (behavior) into
packages called classes
– data and functions closely related

• Information hiding
– implementation details are hidden within the classes themselves

• Unit of programming - the class


– 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”

© 2000 Deitel & Associates, Inc. All rights reserved.


Structure Definitions (I)
• Structures
– aggregate data types built using elements of other types including other
structs

struct Time { Structure tag


int hour;
int minute; Structure members
int second;
};

• Members of the same structure must have unique names


• Two different structures may contain members of the same name
• Each structure definition must end with a semicolon.

© 2000 Deitel & Associates, Inc. All rights reserved.


Structure Definitions (II)

• self-referential structure
– Contains a member that is a pointer to the same structure type
– Used for linked lists, queues, stacks and trees

• Struct
– creates a new data type that is used to declare variables.
– Structure variables are declared like variables of other types
– For example:
Time timeObject, timeArray[ 10 ], *timePtr,
&timeRef = timeObject;

© 2000 Deitel & Associates, Inc. All rights reserved.


Accessing Members of Structures

• member access operators:


– dot operator (.) for structures and objects
– arrow operator (->) for pointers

• Print member hour of timeObject:


cout << [Link];
OR
timePtr = &timeObject; // timePtr ptr to
timeObject
cout << timePtr->hour; // prints [Link]

• timePtr->hour same as (*timePtr).hour

• Parentheses required: (*) has lower precedence than (.)

© 2000 Deitel & Associates, Inc. All rights reserved.


1 // Fig. 6.1: fig06_01.cpp
2 // Create a structure, set its members, and print it. Outline
3 #include <iostream>
4
5 using std::cout;
1. Define the struct
6 using std::endl;
7
8 struct Time { // structure definition
9 int hour; // 0-23 1.1 Define prototypes
10 int minute; // 0-59 for the functions.
11 int second; // 0-59
Creates the user-defined structure
12 };
type Time with three integer
members: hour, minute and 2. Create a struct data
13
type
14 void printMilitary( const Time & ); second // prototype
15 void printStandard( const Time & ); // prototype
16
17 int main() 2.1 Set and print the
18 { time.
19 Time dinnerTime; // variable of new type Time
20
21 // set members to valid values
22 [Link] = 18;
23 [Link] = 30;
24 [Link] = 0;
25
26 cout << "Dinner will be held at ";
27 printMilitary( dinnerTime ); Dinner will be held at 18:30 military time,
28 cout << " military time,\nwhich is "; which is [Link] PM standard time.
29 printStandard( dinnerTime );
30 cout << " standard time.\n";
© 2000 Deitel & Associates, Inc. All rights reserved.
31
32 // set members to invalid values
33 [Link] = 29; Outline
34 [Link] = 73;
35
2.2 Set the time to an
36 cout << "\nTime with invalid values: "; invalid hour, then print it.
37 printMilitary( dinnerTime );
Time with invalid values: 29:73
38 cout << endl;
39 return 0; 3. Define the functions
40 } printMilitary and
41 printStandard.
42 // Print the time in military format
43 void printMilitary( const Time &t )
44 {
45 cout << ( [Link] < 10 ? "0" : "" ) << [Link] << ":"
46 << ( [Link] < 10 ? "0" : "" ) << [Link];
47 }
48
49 // Print the time in standard format
50 void printStandard( const Time &t )
51 {
52 cout << ( ( [Link] == 0 || [Link] == 12 ) ?
53 12 : [Link] % 12 )
54 << ":" << ( [Link] < 10 ? "0" : "" ) << [Link]
55 << ":" << ( [Link] < 10 ? "0" : "" ) << [Link]
56 << ( [Link] < 12 ? " AM" : " PM" );
© 2000
57 } Deitel & Associates, Inc. All rights reserved.
Dinner will be held at 18:30 military time,
Outline
which is [Link] PM standard time.

Time with invalid values: 29:73

Program Output

© 2000 Deitel & Associates, Inc. All rights reserved.


Implementing a Time Abstract Data Type with a
Class (I)
• Model objects that have attributes (data members) and behaviors (member functions).
• defined using keyword class
• The body delineated with braces ({ and }).
• Class definition terminates with a semicolon. For 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.
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.
• Member functions and data can be:
Public - accessible wherever the program has access to an object of class Time.
Private - accessible only to member functions of the class.
Protected - discussed later in the course.

© 2000 Deitel & Associates, Inc. All rights reserved.


Implementing a Time Abstract Data Type with a
Class (II)

• constructor - special member function that initializes the data members


of a class object.
– Constructors cannot return values.
– same name as the class
• Once the class has been defined, it can be used as a type in object,
array and pointer definitions as follows:
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.

© 2000 Deitel & Associates, Inc. All rights reserved.


1 // Fig. 6.3: fig06_03.cpp
2 // Time class. Outline
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 1. Define a Time class
17 int minute; // 0 – 59
18 int second; // 0 – 59
1.1 Define default values
19 };
20
for the time.
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; }
Note the ::
24 preceding the
25 // Set a new Time value using military time. Perform validity function names
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 } Deitel & Associates, Inc. All rights reserved.
2000
33
34 // Print Time in military format Outline
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 ) 1.2 Define the two
45 << ":" << ( minute < 10 ? "0" : "" ) << minute functions
46 << ":" << ( second < 10 ? "0" : "" ) << second printMilitary and
47 << ( hour < 12 ? " AM" : " PM" ); printstandard.
48 }
49
50 // Driver to test simple class Time 2. In main(), create an
51 int main() object of class Time.
52 {
53 Time t; // instantiate object t of class The
Timeinitial military time 2.1
is 00:00
Print the initial
54 The initial standard time (default)
is [Link]
[Link]
55 cout << "The initial military time is ";
56 [Link](); Notice how functions
57 cout << "\nThe initial standard time is "; are called using the
58 [Link]();
dot ( . ) operator.
59

© 2000 Deitel & Associates, Inc. All rights reserved.


60 [Link]( 13, 27, 6 );
61 cout << "\n\nMilitary time after setTime is "; Outline
62 [Link]();
63 cout << "\nStandard time after setTime is ";
64 [Link]();
Military time after setTime is 13:27
65
Standard time after setTime is [Link] PM
66 [Link]( 99, 99, 99 ); // attempt invalid settings
67 cout << "\n\nAfter attempting invalid settings:"
68 << "\nMilitary time: "; 2.2 Set and print the
69 [Link](); time.
70 cout << "\nStandard time: ";
71 [Link](); After attempting invalid settings: 2.3 Attempt to set the
72 cout << endl; time to an invalid hour,
Military time: 00:00
73 return 0;
Standard time: [Link] AM then print what it
74 }
actually gets set to.

The initial military time is 00:00


The initial standard time is [Link] AM

Military time after setTime is 13:27


Standard time after setTime is [Link] PM

After attempting invalid settings:


Military time: 00:00 Program Output
Standard time: [Link] AM

© 2000 Deitel & Associates, Inc. All rights reserved.


Implementing a Time Abstract Data Type with a
Class (III)

• A class’ private data members are normally not accessible outside


the class.

• The binary scope resolution operator (::) - specifies which class


owns the member function (different classes can have the same name
for member functions).

• Format for definition class member functions:


ReturnType ClassName::MemberFunctionName( ){

}

© 2000 Deitel & Associates, Inc. All rights reserved.


Implementing a Time Abstract Data Type with a
Class (IV)

• 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

• In this program, the Time constructor simply initializes


the data members to 0
– This ensures that the object is in a consistent state when it is created.

• Classes encourage software reuse


– Inheritance allows new classes to be derived from old ones.

© 2000 Deitel & Associates, Inc. All rights reserved.


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 - use handles
– an object name, a reference to an object or a pointer to an object.
• Function scope
– variables defined in member functions, destroyed after function completes.
• Accessing class members- same as structs.
– Dot (.) for objects and arrow (->) for pointers.
– Example: [Link] is the hour element of t.
– TimePtr->hour is the hour element.

© 2000 Deitel & Associates, Inc. All rights reserved.


1 // Fig. 6.4: fig06_04.cpp
2 // Demonstrating the class member access operators . and -> Outline
3 //
4 // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA!
5 #include <iostream> It is rare to have
6 public member
7 using std::cout;
variables. Usually
8 using std::endl;
only member
9
functions are
10 // Simple class Count
public; this 1. Define a class
11 class Count {
12 public: keeps as much to have a data member
13 int x; information hidden and a print function.
14 void print() { cout << x << endl; } as possible.
15 }; 2. Create an object of the
16 class.
17 int main()
18 {
2.1 Assign a value to the
19 Count counter, // create counter object
object. Print the value
20 *counterPtr = &counter, // pointer to counter
using the dot operator.
21 &counterRef = counter; // reference to counter
22
23 cout << "Assign 7 to x and print using the object's name: "; 2.2 Set a new value and
24 counter.x = 7; // assign 7 to data member x print it using a reference.
25 [Link](); // 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 [Link](); // call member function print
© 2000 Deitel & Associates, Inc. All rights reserved.
30
31 cout << "Assign 10 to x and print using a pointer: ";
32 counterPtr->x = 10; // assign 10 to data member x Outline
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

2.3 Set a new value and


print it using a pointer.

Program Output

© 2000 Deitel & Associates, Inc. All rights reserved.


Separating Interface from Implementation

• Separating interface from implementation makes it easier to modify


programs. C++ programs can be split into:
Header files – contains class definitions and function prototypes
Source-code files – contains member function definitions.

• Psuedocode Outline:

1. Using the same Time class as before, create a header file.


2. Create a source code file.
2.1 Load the header file to get the class definitions.
2.2. Define the member functions of the class.

© 2000 Deitel & Associates, Inc. All rights reserved.


1 // Fig. 6.5: time1.h
2 // Declaration of the Time class. Outline
3 // Member functions are defined in [Link]
4
5 // prevent multiple inclusions of header file
6 #ifndef TIME1_H Dot ( . ) replaced with underscore ( _ ) in file
7 #define TIME1_H name.
8
If time1.h (TIME1_H) is not defined
9 // Time abstract data type definition
(#ifndef) then it is loaded (#define
10 class Time { TIME1_H). If TIME1_H is already
11 public: defined, then everything up to #endif is
12 Time(); // constructor ignored.
13 void setTime( int, int, int ); // set hour, minute, second 1. Using
This prevents loading a header file Time
the same
14 void printMilitary(); //
class as before, create a
print military time format multiple times.
header file .
15 void printStandard(); // print standard time format
16 private:
17 int hour; // 0 - 23
18 int minute; // 0 - 59
19 int second; // 0 - 59
20 };
21
22 #endif

© 2000 Deitel & Associates, Inc. All rights reserved.


23 // Fig. 6.5: [Link]
24 // Member function definitions for Time class.
25 #include <iostream>
Outline
26
27 using std::cout;
28 Source file uses #include
29 #include "time1.h"
30
to load the header file
31 // Time constructor initializes each data member to zero.
32 // Ensures all Time objects start in a consistent state.
33 Time::Time() { hour = minute = second = 0; }
34
35 // Set a new Time value using military time. Perform validity
36 // checks on the data values. Set invalid values to zero.
37 void Time::setTime( int h, int m, int s ) 2. Create a source code
38 { file.
39 hour = ( h >= 0 && h < 24 ) ? h : 0;
40 minute = ( m >= 0 && m < 60 ) ? m : 0;
41 second = ( s >= 0 && s < 60 ) ? s : 0; 2.1 Load the header file
Source file contains
42 } to get the class
43 function definitions
definitions.
44 // Print Time in military format
45 void Time::printMilitary()
46 { 2.2. Define the member
47 cout << ( hour < 10 ? "0" : "" ) << hour << ":" functions of the class.
48 << ( minute < 10 ? "0" : "" ) << minute;
49 }
50
51 // Print time in standard format
52 void Time::printStandard()
53 {
54 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
55 << ":" << ( minute < 10 ? "0" : "" ) << minute
56 << ":" << ( second < 10 ? "0" : "" ) << second
57 << ( hour < 12 ? " AM" : " PM" );
© 2000
58 } Deitel & Associates, Inc. All rights reserved.
Controlling Access to Members

• Purpose of public
– present 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.

© 2000 Deitel & Associates, Inc. All rights reserved.


1 // Fig. 6.6: fig06_06.cpp
2 // Demonstrate errors resulting from attempts Outline
3 // to access private class members.
4 #include <iostream>
5
6 using std::cout;
7
8 #include "time1.h"
9
10 int main() 1. Load header file for
11 { Time class.
12 Time t;
13 2. Create an object of
14 // Error: 'Time::hour' is not accessible class Time.
15 [Link] = 7; Attempt to modify private member
16 variable hour
17 // Error: 'Time::minute' is not accessible 2.1 Attempt to set a
18 cout << "minute = " << [Link]; private variable
19 Attempt to access private member
20 return 0; variable minuteto access a
2.2 Attempt
21 }
private variable.

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'
Program Output
D:\time1.h(19) : see declaration of 'minute'
Error executing [Link].

[Link] - 2 error(s), 0 warning(s)


© 2000 Deitel & Associates, Inc. All rights reserved.
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

© 2000 Deitel & Associates, Inc. All rights reserved.


87 // Fig. 6.7: fig06_07.cpp
88 // Demonstrating a utility function Outline
89 // Compile with [Link]
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 [Link](); // note simple sequential code
97 [Link](); // no control structures in main 1. Load header file and
98 return 0; compile with the file that
99 } contains the function
Use access functions to gather
definitions.
OUTPUT and print data
Enter sales amount for month 1: 5314.76 (getSalesFromUser
Enter sales amount for month 2: 4292.38
2. Create an [Link]
Enter sales amount for month 3: 4589.83 printAnnualSales). Utility
Enter sales amount for month 4: 5534.03 functions
2.1 actually
Use thecalculate
object’s the
Enter sales amount for month 5: 4376.34 total sales, but functions
the user isto
not
Enter sales amount for month 6: 5698.45
member get
Enter sales amount for month 7: 4439.22 awareand
of these
print function
sales. calls.
Enter sales amount for month 8: 5893.57
Enter sales amount for month 9: 4909.67 Notice how simple main() is –
Program Output
Enter sales amount for month 10: 5123.45 there are no control structures,
Enter sales amount for month 11: 4024.97 only function calls. This hides
Enter sales amount for month 12: 5923.92
the implementation of the
The total annual sales are: $60120.59 program.

© 2000 Deitel & Associates, Inc. All rights reserved.


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.

• When an object of a class is declared, initializers can be


provided.
– These initializers are passed as arguments to the class’ constructor.
• Format:
Type ObjectName(value1,value2,…);

© 2000 Deitel & Associates, Inc. All rights reserved.


Initializing Class Objects: Constructors (II)

• constructor assigns value1, value2, etc. to its


member variables.
– If not enough values specified, rightmost parameters set to default

• Default arguments
– set in constructor function prototype (in the class definition)

© 2000 Deitel & Associates, Inc. All rights reserved.


1 // Fig. 6.8: time2.h
2 // Declaration of the Time class. Outline
3 // Member functions are defined in [Link]
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: Notice that default settings
13 Time( int = 0, int = 0, int = 0 ); // default constructor for the three member
14 void setTime( int, int, int ); // set hour, minute, second 1. variables are Time
Define class set in and
15 void printMilitary(); // print military time format
constructor
its default prototype.
values. No
names are needed; the
16 void printStandard(); // print standard time format
defaults are applied in the
17 private:
order the member variables
18 int hour; // 0 - 23 are declared.
19 int minute; // 0 - 59
20 int second; // 0 - 59
21 };
22
23 #endif

© 2000 Deitel & Associates, Inc. All rights reserved.


61 // Fig. 6.8: fig06_08.cpp
62 // Demonstrating a default constructor Outline
63 // function for class Time.
64 #include <iostream>
65 Notice how objects are initialized:
66 using std::cout; Constructor ObjectName(value1,value2…);
67 using std::endl; If not enough values are specified, the rightmost
68
values are set to their defaults.
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 2. Create objects using
78
default arguments.
79 cout << "Constructed with:\n"
80 << "all arguments defaulted:\n ";
81 [Link](); 2.1 Print the objects.
82 cout << "\n ";
83 [Link]();
84
85 cout << "\nhour specified; minute and second defaulted:"
86 << "\n ";
87 [Link]();
88 cout << "\n ";
89 [Link]();
90
91 cout << "\nhour and minute specified; second defaulted:"
92 << "\n ";
©
93 2000 Deitel & Associates,
[Link](); Inc. All rights reserved.
94 cout << "\n ";
95 [Link]();
96 Outline
97 cout << "\nhour, minute, and second specified:"
98 << "\n ";
99 [Link]();
100 cout << "\n ";
101 [Link]();
102
103 cout << "\nall invalid values specified:"
104 << "\n "; 2.1 (continued) Print the
105 [Link](); objects.
106 cout << "\n ";
107 [Link]();
108 cout << endl;
109
110 return 0;
111 }
OUTPUT
Constructed with:
When only hour
all arguments defaulted: is specified,
00:00 minute and
[Link] AM
hour specified; minute and second defaulted:
second are set
02:00 to their default
[Link] AM values of 0.
hour and minute specified; second defaulted: Program Output
21:34
[Link] PM
hour, minute, and second specified:
12:25
[Link] PM
all invalid values specified:
00:00
© 2000
[Link]
Deitel &AM
Associates, Inc. All rights reserved.
Using Destructors

• Destructor –member function of class


– performs 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

© 2000 Deitel & Associates, Inc. All rights reserved.


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

© 2000 Deitel & Associates, Inc. All rights reserved.


When Constructors and Destructors Are Called (II)

• automatic local objects


– Constructors called when objects defined
– Destructors called when objects leave scope (when the block in which
they are defined is exited)
– Destructors not called if 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

© 2000 Deitel & Associates, Inc. All rights reserved.


1 // Fig. 6.9: create.h
2 // Definition of class CreateAndDestroy. Outline
3 // Member functions defined in [Link].
4 #ifndef CREATE_H
5 #define CREATE_H
6
7 class CreateAndDestroy {
8 public:
9 CreateAndDestroy( int ); // constructor
10 ~CreateAndDestroy(); // destructor
11 private:
12 int data; Destructor:
13 }; 1. Create a header file.
14
-Receives no parameters
15 #endif 1.1 Include function
-Returns no value
prototypes for the
-Has a tilde (~)destructor
then the and
class name
as its nameconstructor.

© 2000 Deitel & Associates, Inc. All rights reserved.


16 // Fig. 6.9: [Link]

17 // Member function definitions for class CreateAndDestroy


Outline
18 #include <iostream>

19

20 using std::cout;

21 using std::endl;

22

23 #include "create.h"

24
2. Load the header file.
25 CreateAndDestroy::CreateAndDestroy( int value )

26 { 2.1 Modify the


Constructor and Destructor
constructor and
27 data = value; changed to print when they
destructor.
are called.
28 cout << "Object " << data << " constructor";

29 }

30

31 CreateAndDestroy::~CreateAndDestroy()

32 { cout << "Object " << data << " destructor " << endl; }

© 2000 Deitel & Associates, Inc. All rights reserved.


33 // Fig. 6.9: fig06_09.cpp
34 // Demonstrating the order in which constructors and Outline
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; 3. Create multiple objects
50 of varying types.
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;
© 2000
62 } Deitel & Associates, Inc. All rights reserved.
63
64 // Function to create objects Outline
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) Program Output
Object 4 destructor constructor and destructor call
Object 2 destructor depends on the types of
Object 6 destructor
Object 3 destructor variables (automatic, global and
Object 1 destructor static) they are associated
with.
© 2000 Deitel & Associates, Inc. All rights reserved.
Using Data Members and Member Functions

• Classes often provide public member functions to allow clients of


the class to set (i.e., write) or get (i.e., read) the values of private
data members.

• A typical manipulation might be the adjustment of a customer’s bank


balance (e.g., a private data member of a class BankAccount) by
a member function computeInterest.

• A member function that sets data member interestRate would


typically be named setInterestRate, and a member function that
gets the interestRate would typically be called
getInterestRate.

© 2000 Deitel & Associates, Inc. All rights reserved.


Using Data Members and Member Functions (II)

• Is providing both set and get capabilities same as


making data members public?
– No. Programmer decides what variables the function can set and
what information the function can get.

• public set function would check attempts to


modify data members.
– ensure that the new value is appropriate for that data item.
– For example, an attempt to set the day of the month to 37 would be
rejected.
– programmer must include these features

© 2000 Deitel & Associates, Inc. All rights reserved.


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.

• One way to use this capability (unfortunately!)


– have a public member function of a class return a non-const
reference to a private data member

© 2000 Deitel & Associates, Inc. All rights reserved.


1 // Fig. 6.11: time4.h
2 // Declaration of the Time class. Outline
3 // Member functions defined in [Link]
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();
1. Define class
15 int &badSetHour( int ); // DANGEROUS reference return
1.1 Function prototypes
16 private:
17 int hour;
1.2 Member variables
18 int minute;
19 int second;
20 };
21
22 #endif

© 2000 Deitel & Associates, Inc. All rights reserved.


23 // Fig. 6.11: [Link]
24 // Member function definitions for Time class. Outline
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 } 1. Load header
40
41 // Get the hour value 1.1 Function definitions
42 int Time::getHour() { return hour; }
badSetHour returns a
43
44 // POOR PROGRAMMING PRACTICE:
reference to the private
45 // Returning a reference to a private data member. member variable hour.
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 }
© 2000 Deitel & Associates, Inc. All rights reserved.
52 // Fig. 6.11: fig06_11.cpp
53 // Demonstrating a public member function that Outline
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;
1.2 Declare reference
59 using std::endl; Declare Time object t and 2. Change data using
60 reference hourRef that is a reference
61 #include "time4.h"
assigned the reference returned by
62 3. Output results
63 int main()
the call [Link](20).
64 {
65 Time t;
66 int &hourRef = [Link]( 20 );
67 Hour before modification: 20
68 cout << "Hour before modification: " << hourRef;
69 hourRef = 30; // modification with invalid value Alias used to set the value
70 cout << "\nHour after modification: " << [Link](); of hour to 30 (an invalid
71 value).
72 // Dangerous: Function call that returns Hour after modification: 30
73 // a reference can be used as an lvalue!
74 [Link](12) = 74; Function call used as an lvalue
75 cout << "\n\n*********************************\n"
and assigned the value 74
76 << "POOR PROGRAMMING PRACTICE!!!!!!!!\n"
77 << "badSetHour as an lvalue, Hour: " (another invalid value).
78 << [Link]()
79 << "\n*********************************" << endl;
*********************************
80
81 return 0; POOR PROGRAMMING PRACTICE!!!!!!!!
82 } badSetHour as an lvalue, Hour: 74
*********************************
© 2000 Deitel & Associates, Inc. All rights reserved.
Hour before modification: 20 Outline
Hour after modification: 30

*********************************
POOR PROGRAMMING PRACTICE!!!!!!!!
badSetHour as an lvalue, Hour: 74
*********************************

HourRef used to change hour


to an invalid value. Normally,
the function setbadSetHour
would not have allowed this.
However, because it returned a
reference, hour was changed Program Output
directly.

© 2000 Deitel & Associates, Inc. All rights reserved.


Assignment by Default Memberwise Copy

• assignment operator (=) sets variables equal, i.e., x = y;

• Can be used to assign an object to another object of the


same type.
– memberwise copy—member by member copy

• objects may be
– passed as function arguments
– returned from functions (call-by-value default).
• Use pointers for call by reference

© 2000 Deitel & Associates, Inc. All rights reserved.


1 // Fig. 6.12: fig06_12.cpp
2 // Demonstrating that class objects can be assigned Outline
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; 1. Define class
18 };
19 1.1 Define member
20 // Simple Date constructor with no range checking
functions
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; }

© 2000 Deitel & Associates, Inc. All rights reserved.


31
32 int main() Outline
33 {
34 Date date1( 7, 4, 1993 ), date2; // d2 defaults to 1/1/90
35
36 cout << "date1 = ";
37 [Link]();
38 cout << "\ndate2 = ";
39 [Link]();
40 2. Create Date objects
41 date2 = date1; // assignment by default memberwise copy
42 cout << "\n\nAfter default memberwise copy, date2 = "; 2.1 Memberwise copy
43 [Link](); date2 set equal to
44 cout << endl; 3. Print values
45
date1, and all member
46 return 0; variables are copied.
47 }

date1 = 7-4-1993
date2 = 1-1-1990

After default memberwise copy, date2 = 7-4-1993

Program Output

© 2000 Deitel & Associates, Inc. All rights reserved.


Software Reusability

• People who write object-oriented programs concentrate on


implementing useful classes.

• Tremendous opportunity to capture and catalog classes


– accessed by large segments of the programming community
– Class libraries exist for this purpose

• Software being constructed from existing, well-defined,


carefully tested, well-documented, portable, widely
available components.
– speeds development of powerful, high-quality software

© 2000 Deitel & Associates, Inc. All rights reserved.

You might also like