Chapter 13

advertisement
CHAPTER 13
CLASSES AND DATA
ABSTRACTION
In this chapter, you will:
 Learn about classes
 Learn about private, protected, and public members
of a class
 Explore how classes are implemented
 Examine constructors and destructors
 Learn about the abstract data type (ADT)
 Explore how classes are used to implement ADT
 Learn about information hiding
 Explore how information hiding is implemented in
C++
CLASSES
 A class is a collection of a fixed number of components.
 The components of a class are called members of the class: member data
(attribute) and/or member function (function).
The general syntax of defining a class is:
class classIdentifier
{
classMemberList
};
 The members of a class are classified into three categories: private, public,
and protected.
 By default, all members of a class are private.
 If a member of a class is private, you cannot access it outside the class.
 A public member is accessible outside the class.
Define a class, clockType, to implement the time of day in a program.
Member Data: Time is represented as a set of three integers: one to represent the hours, one to
represent the minutes, and one to represent the seconds.
Member Function: Perform the following operations on the time:
1. Set the time.
2. Return the time.
3. Print the time.
4. Increment the time by one second.
5. Increment the time by one minute.
6. Increment the time by one hour.
7. Compare the two times for equality.
class clockType
{
public:
void setTime(int, int, int);
void getTime(int&, int&, int&);
void printTime() const;
void incrementSeconds();
void incrementMinutes();
void incrementHours();
bool equalTime(const clockType& otherTime) const;
private:
int hr;
int min;
int sec;
};
•The seven function member can directly access the private data members (hr, min, and
sec).
•In the function equalTime, the parameter otherTime is a constant reference parameter.
That is, in a call to the function equalTime, the parameter otherTime receives the
address of the actual parameter, but otherTime cannot modify the value of the actual
parameter.
•The word const at the end of the member functions printTime and equalTime specifies
that these functions cannot modify the data members of a variable of the type
clockType.
Variable (Object) Declaration
Once a class is defined, you can declare variables of that type.
In C++ terminology, a class variable is called a class object or class
instance.
clockType
myClock;
clockType
yourClock;
Accessing Class Members
In C++, the dot, . (period), is an operator called the member access
operator.
myClock.setTime(5,2,30);
myClock.printTime();
yourClock.setTime(x,y,z);
//Assume x, y, and
//z are variables of the type int
if(myClock.equalTime(yourClock))
.
.
.
myClock.hr = 10;
myClock.min = yourClock.min;
//illegal
//illegal
Built-in Operations on Classes
 Most of C++’s built-in operations do not apply to classes.
 You cannot use arithmetic operators to perform arithmetic
operations on class objects (unless they are overloaded).
 For example, you cannot use the operator + to add two class objects
of, say, the type clockType.
 Also, you cannot use relational operators to compare two class
objects for equality.
 The two built-in operations that are valid for class objects are
member access (.) and assignment (=).
The Assignment Operator and Classes
myClock = yourClock;
copies the value of yourClock into myClock
a. the value of yourClock.hr is copied into myClock.hr,
b. the value of yourClock.min is copied into myClock.min
c. the value of yourClock.sec is copied into myClock.sec
Class Scope
• A class variable has the same scope as other variables.
• A member of a class is local to the class.
Functions and Classes
 Class objects can be passed as parameters to functions and returned as function
values.
 As parameters to functions, classes can be passed either by value or by reference.
 If a variable is passed by value, the corresponding formal parameter receives a
copy of the data of the variable.
 If a variable is passed by reference, the formal parameter receives only the address
of the actual parameter.
 In C++, you can pass a variable by reference and still prevent the function from
changing its value, by using the keyword const in the formal parameter
declaration.
void testTime(const clockType& otherClock)
{
clockType dClock;
...
}
Implementation of Member Functions
• In the heading of the function definition, the name of the function is
the name of the class followed by the scope resolution operator
followed by the function name.
void clockType::setTime(int hours, int minutes,
int seconds)
{
if(0 <= hours && hours < 24)
hr = hours;
else
hr = 0;
if(0 <= minutes && minutes < 60)
min = minutes;
else
min = 0;
if(0 <= seconds && seconds < 60)
sec = seconds;
else
sec = 0;
}
void clockType::printTime() const
{
if(hr < 10)
cout<<"0";
cout<<hr<<":";
if(min < 10)
cout<<"0";
cout<<min<<":";
if(sec < 10)
cout<<"0";
cout<<sec;
}
void clockType::getTime(int& hours, int& minutes,
int& seconds)
{
hours = hr;
minutes = min;
seconds = sec;
}
void clockType::incrementHours()
{
hr++;
if(hr > 23)
hr = 0;
}
void clockType::incrementMinutes()
{
min++;
if(min > 59)
{
min = 0;
incrementHours();
}
}
void clockType::incrementSeconds()
{
sec++;
if(sec > 59)
{
sec = 0;
incrementMinutes();
}
}
bool clockType::equalTime(const clockType& otherClock)
const
{
return (hr == otherClock.hr
&& min == otherClock.min
&& sec == otherClock.sec);
}
//Program that uses the class clockType
int main()
{
clockType myClock;
clockType yourClock;
int hours;
int minutes;
int seconds;
myClock.setTime(5,4,30);
cout<<"Line 2: myClock: ";
myClock.printTime();
cout<<endl;
cout<<"Line 5: yourClock: ";
yourClock.printTime();
cout<<endl;
yourClock.setTime(5,45,16);
//Line
//Line
//Line
//Line 4
//Line 5
//Line 6
//Line 7
//Line
1
2
3
8
cout<<"Line 9: After setting - yourClock: "; //Line 9
yourClock.printTime();
//Line 10
cout<<endl;
//Line 11
if(myClock.equalTime(yourClock))
//Line
cout<<"Line 13: Both times are equal."
<<endl;
//Line
else
//Line
cout<<"Line 15: The two times are not equal"
<<endl;
//Line
12
13
14
15
cout<<"Line 16: Enter hours, minutes, and "
<<"seconds: ";
//Line 16
cin>>hours>>minutes>>seconds;
//Line 17
cout<<endl;
//Line 18
myClock.setTime(hours,minutes,seconds); //Line 19
cout<<"Line 20: New myClock: ";
myClock.printTime();
cout<<endl;
myClock.incrementSeconds();
//Line 20
//Line 21
//Line 22
//Line 23
cout<<"Line 24: After incrementing the clock by "
<<"one second, myClock: ";
//Line 24
myClock.printTime();
cout<<endl;
return 0;
}//end main
Output: The user input is in red.
Line 2: myClock: 05:04:30
Line 5: yourClock: (The value of yourClock is undefined here).
Line 9: After setting - yourClock: 05:45:16
Line 15: The two times are not equal
Line 16: Enter hours, minutes, and seconds: 5 23 59
Line 20: New myClock: 05:23:59
Line 24: After incrementing the time by one second, myClock: 05:24:00
//Line 25
//Line 26
Order of Public and Private Members of a Class
Example 13-3
class clockType
{
public:
void setTime(int, int, int);
void getTime(int&, int&, int&);
void printTime() const;
void incrementSeconds();
void incrementMinutes();
void incrementHours();
bool equalTime(const clockType&) const;
private:
int hr;
int min;
int sec;
};
Example 13-4
class clockType
{
private:
int hr;
int min;
int sec;
public:
void setTime(int, int, int);
void getTime(int&, int&, int&);
void printTime() const;
void incrementSeconds();
void incrementMinutes();
void incrementHours();
bool equalTime(const clockType&) const;
};
Example 13-5
class clockType
{
int hr;
int min;
int sec;
public:
void
void
void
void
void
void
bool
};
setTime(int, int, int);
getTime(int&, int&, int&);
printTime() const;
incrementSeconds();
incrementMinutes();
incrementHours();
equalTime(const clockType&) const;
Constructors
We can guarantee the initialization of the data members of a class by
using constructors.
• There are two types of constructors: with parameters and without
parameters.
• The constructor without parameters is called the default
constructor.
1. The name of a constructor is the same as the name of the class.
2. A constructor has no return type.
3. A class can have more than one constructor. However, all constructors
of a class have the same name.
4. If a class has more than one constructor, they must have different sets
of parameters.
5. Constructors are automatically executed when a class variable enters
its scope.
6. Which constructor executes depends on the type of values passed to
the class variable when the class variable is declared.
class clockType
{
public:
void setTime(int, int, int);
void getTime(int&, int&, int&);
void printTime() const;
void incrementSeconds();
void incrementMinutes();
void incrementHours();
bool equalTime(const clockType&) const;
clockType(int, int, int);
//constructor with parameters
clockType(); //default constructor
private:
int hr;
int min;
int sec;
};
clockType::clockType(int hours, int minutes, int seconds)
{
if(0 <= hours && hours < 24)
hr = hours;
else
hr = 0;
if(0 <= minutes && minutes < 60)
min = minutes;
else
min = 0;
}
if(0 <= seconds && seconds < 60)
sec = seconds;
else
sec = 0;
clockType::clockType()
{
hr = 0;
min = 0;
sec = 0;
}
//default constructor
Invoking a Constructor
• A constructor is automatically executed when a class variable is declared.
• A class might have more than one constructor, including the default constructor.
clockType yourClock;
declares yourClock to be a variable of the type clockType. In this case, the default constructor is
executed and the data members of yourClock will be initialized to zero.
clockType myClock(5,12,40);
This statement declares a class variable myClock.
In this case, the constructor with parameters of the class clockType will be executed and the three data
members of the variable myClock will be set to 5, 12, and 40.
class testClass
{
public:
void print();
//Line a
testClass();
testClass(int, int);
testClass(int, double, int); //Line d
testClass(double, char);
//Line b
//Line c
//Line e
private:
int x;
int y;
double z;
char ch;
};
void testClass::print()
{
cout<<"x = "<<x<<", y = "<<y<<", z = "<<z
<<", ch = "<<ch<<endl;
}
testClass::testClass()
{
x = 0;
y = 0;
z = 0;
ch = '*';
}
//default constructor
testClass::testClass(int a, int b)
{
x = a;
y = b;
z = 0;
ch = '*';
}
testClass::testClass(int a, double c, int b)
{
x = a;
y = b;
z = c;
ch = '*';
}
testClass::testClass(double c, char d)
{
x = 0;
y = 0;
z = c;
ch = d;
}
testClass
testClass
testClass
testClass
testClass
one;
two(5,6);
three(5,4.5,7);
four(4,9,12);
five(3.4,'D');
int main()
{
testClass
testClass
testClass
testClass
testClass
one;
two(5,6);
three(5,4.5,7);
four(4,9,12);
five(3.4,'D');
one.print();
two.print();
three.print();
four.print();
five.print();
//Line
//Line
//Line
//Line
//Line
1
2
3
4
5
//Line
//Line
//Line
//Line
//Line
1
2
3
4
5
//Line
//Line
//Line
//Line
//Line
6; output one
7; output two
8; output three
9; output four
10; output five
return 0;
}
Output
x
x
x
x
x
=
=
=
=
=
0,
5,
5,
4,
0,
y
y
y
y
y
=
=
=
=
=
0, z = 0, ch = *
6, z = 0, ch = *
7, z = 4.5, ch = *
12, z = 9, ch = *
0, z = 3.4, ch = D
 A constructor that has no parameters, or has all default parameters, is
called the default constructor.
Example 13-7
class testClass
{
public:
void print();
testClass(int = 0, double = 0.0, int = 0, char = '*');
private:
int x;
int y;
double z;
char ch;
};
Arrays of Class Objects (Variables) and Constructors
 If a class has constructors and you declare an array of class objects,
the class must have the default constructor.
 The default constructor is used to initialize each (array) class object.
clockType clocks[100];
Destructors
 Like constructors, destructors are also functions.
 The name of a destructor is the character '~' followed by the name
of the class.
 The name of the destructor for the class clockType is
~clockType();
 A class can have only one destructor and it has no parameters.
 The destructor is automatically executed when the class object goes
out of scope.
A STRUCT VERSUS A CLASS
 By default the members of a struct are public.
 By default the members of a class are private.
 You can use the member access specifier private in a struct to make a member
private.
 Both C++ classes and structs have the same capabilities.
 If all of the data members of a class are public and the class has no member functions,
you typically use a struct to group these members.
INFORMATION HIDING
 Implementation file.
 Header file (Specification file).
 The header file has an extension h.
 The implementation file has an extension cpp.
 The implementation file must include the header file via the include statement.
 In a include statement, user defined header files are enclosed in double quotes while system
provided header files are enclosed between angular brackets.
//clock.h, the specification file for the class clockType
class clockType
{
public:
void setTime(int hours, int minutes, int seconds);
void getTime(int& hours, int& minutes, int& seconds)
void printTime() const;
void incrementSeconds();
void incrementMinutes();
void incrementHours();
bool equalTime(const clockType& otherClock) const;
clockType(int hours, int minutes, int seconds);
clockType();
private:
int hr; //store hours
int min; //store minutes
int sec; //store seconds
};
//clockImp.cpp, the implementation file
#include <iostream>
#include "clock.h"
using namespace std;
.
.
.
//The definition of the member functions of the clockType //goes here.
.
.
.
.
To use the class clockType, the program must include the header file clock.h via the include statement.
//Place the definitions of the function main and the other
//user-defined functions here
.
//Program test.cpp
#include <iostream>
.
.
#include "clock.h”
using namespace std;
int main()
{
.
.
.
}
To create the executable code to run the program test.cpp, the following steps are required:
1. Separately compile the file clockImp.cpp and create the object code file clockImp.obj. Suppose the
command cc invokes the C++ compiler or linker, or both, on the computer’s system command line. The command
cc –c clockImp.cpp
creates the object code file clockImp.obj.
2. To create the executable code for the source code file test.cpp, compile the source code file test.cpp, create
the object code file test.obj, and then link the files test.obj and clockImp.obj to create the executable file
test.exe. The following command on the system command line creates the executable file test.exe:
cc test.cpp clockImp.obj
 SDK’s Visual C++, C++ Builder, and CodeWarrior put the editor,
compiler, and linker all into one package.
 With one command, the program is compiled and linked with the
other necessary files.
 These systems also manage multiple file programs in the form of a
project.
 A project consists of several files, called the project files.
 These systems usually have a command, called build, rebuild, or
make.
 When the build, rebuild, or make command is applied to a project,
the system automatically compiles and links all files required to
create the executable code.
 When one or more files in the project change, you can use these
commands to recompile and relink the files.
Download