You are on page 1of 25

Chapter XXXIV

Introduction to Data Abstraction

Chapter XXXIV Topics


34.1 Introduction

34.2 Data Type Vocabulary

34.3 Information Hiding

34.4 An ADT Free Response Example

34.5 Data Abstraction and Objects

34.1 Introduction

Chapter XXXIV Introduction to Data Abstraction 34.1


For more than two semesters you have been in a computer science course. Many
students make the mistake of thinking that they are in a C++ course. Such a
mistake is natural, considering that the title of your text books have been
Exposure C++. There have been various stages where you could see more
clearly that you were learning computer science with the aid of C++. You learned
program design concepts that were not language dependent. There was also a
chapter on algorithms about a variety of sorting and searching routines. The logic
of these algorithms could be applied to any language. Sorting and searching is
not part of C++; it is part of computer science.

Whatever you believed in the past, be assured that you are learning computer
science and the programming language we use to teach computer science
concepts is C++. The choice of the language is often debated by people, just as
the previous choice, Pascal, was frequently debated. Our choice of C++ is simply
dictated by the fact that the AP Computer Science Examination is given in C++.
This is one reason why you have seen various examination alerts sprinkled
throughout the chapters. Currently there are various people who feel that a switch
to Java should be made, and if in fact the examination switches to Java or some
other language in the future, then the language used will change.

When you finished Part III of this Exposure C++ series, you finished learning
most of the C++ syntax. Starting with Part IV the emphasis with be primarily on
computer science concepts. Now, we will continue to use C++ for all the
program examples, and you will see programs in C++ that you have not seen
before. But there will not be many new C++ keywords, functions or capabilities
introduced anymore. You have learned the majority of C++ that is going to be
introduced in this course.

The real power of a programming language is not so much which tools are
available in a language, as how many different tools can you create with the
language. You saw evidence of that in the OOP section. We created an array
class from scratch. You may not really like that example because C++ does
provide us with an array data structure. Yet you saw that C++ gave us the tools to
create a better, safer array with greater capabilities.

In the chapters to come, you will be using, and creating stacks, queues, linked
lists, binary trees, circular lists, priority queues and hashing tables. Right now
this looks like a list of strange sounding names. All these names have one simple
feature in common: they are data structures that do not exist in C++. You need
them, you want them, so you must create them. Using and implementing many
different data structures is the goal of the remaining chapters.

Chapter XXXIV Introduction to Data Abstraction 34.2


34.2 Data Type Vocabulary

Computer science has its share of vocabulary, and object oriented programming
did little to reduce the definition list that started long ago in Chapter I. This
chapter starts a new unit in the computer science course and it is important that
you are on solid ground with the vocabulary that will be used. Abstract data types
is the title of this fourth unit and the focus is heavily on taking control of the data
types that we use and can create in programming. I propose to back up to the
beginning and take another look at the various data types introduced along the
computer science journey.

Data Type Definition

A data type is an indicator of both the kind of information that


will be stored, and how much memory space this information
will occupy.

Variable Definition

A variable is a location in memory which stores values. The


memory size and kind of data stored is determined by the
specified data type.

Ouch, that was a bad start. You used to think that these books were not half bad
because they used simple language. That data type definition and variable
definition is less than terrific. Both definitions are presented together because
they work so much together. The definitions are short but think about it. The
purpose of data types is to let the compiler know how much memory needs to be
allocated.

The statement cout << ”811 Fleming Trail” << endl; displays a street address.
A data type is not necessary to display that literal string. On the other hand, if
there are numerous addresses to print on mailing labels, these multiple addresses
will need to be stored in some manner. The storage is done with a variable of
some data type that is suitable for the job. So information is stored in memory,
and to identify that information a variable identifier must be provided.

Chapter XXXIV Introduction to Data Abstraction 34.3


Now it is not sufficient to use just a variable identifier by itself. The language
compiler, C++ in this case, needs to know more about the nature of the values that
will be stored. This means that along with a variable identifier we also specify
what kind of information will be stored, such as an int, float, char, double or
perhaps a more involved data structure such as a struct, apvector or class.

The data type definition states that the memory size is determined by the data
type. This part is very important. Consider for instance an integer. What is the
size of an integer? In mathematical terms it is infinity. In C++ terms - for many
compilers - it is 2 bytes with a range well below infinity. The point is that the
specific compiler that you are using knows the specifications for each data type
that you use. If the data type is more complex and composed of many other
components, then the individual components are added up for the total data type
requirements.

Simple Data Type Definition

A simple data type is a data type that holds a single value.

C++ provides the following simple data types:

char 1 byte
bool 1 byte
int 2 bytes
long 4 bytes
float 4 bytes
double 8 bytes

There should be little difficulty with this definition. A simple data type holds a
single value, period. There is no fancy arithmetic; there are not any
complications because every simple data type has its own specified memory
requirement.

First Data Structure Definition

Chapter XXXIV Introduction to Data Abstraction 34.4


A data structure is a data type whose components are
smaller data structures and/or simple data types.

Do you remember that first data structure definition? The main point of the first
definition was to drill home that a data structure is used to store more than one
value. Furthermore, the complexity of a data structure can be such that a large
data structure is created with smaller data structures as components, and each one
of the smaller data structures is made up of simple data types. That first definition
did fine for starters but it had some fundamental problems that do not properly
explain the true nature of a data structures. Later another definition was presented
that explained the data structure in greater detail.

Improved Data Structure Definition

A data structure is a data type whose components are


smaller data structures and/or simple data types. The
storing and retrieval of the data elements is performed by
accessing functions that characterize the data structure.

The improved data structure definition was less comfortable when it was first
introduced and it may be less comfortable right now. Basically, it is saying that it
is lovely to talk about the values that are stored, but there is also the issue of how
do you access those values for data processing. There is quite a difference in the
manner that you access different data structures. An individual element of a
record (struct in C++) is with a field identifier and period syntax like
Student.Name. Accessing an array element requires knowledge of the element’s
index and the use of bracket syntax like Student[100].

C++ Data Structures

Chapter XXXIV Introduction to Data Abstraction 34.5


C++ data structures are data structures that are made
available by the language. No additional effort is required
to use these data structures, besides the knowledge of
the correct syntax.

The C++ data structures are:

record, which can be implemented with struct or class


array
string (newer compilers)
file

The data structures provided by a programming language are not always the same.
The language BASIC does not have a record. The language Pascal provides the
same basic data structures as C++ and also the Set. Newer version of C++ also
add the string data structure.

Additionally, the College Board has provided a group of data structures to make
learning computer science with C++ easier. They are called the AP classes. You
have already used some of these classes.

With the use of these classes it is also possible to examine students in a consistent
manner by providing questions that all use the same data structures. You will find
that many future C++ compilers will include new data structures that will very
strongly resemble the current AP classes.

AP Classes

AP classes are data structures that provide additional or

Chapter XXXIV Introduction to Data Abstraction 34.6


improved capabilities to the existing C++ data structures.
These classes are data structures that will be included
in future C++ compilers. The AP classes are provided by
the College Board and Educational Testing Service for
AP Computer Science Students.

The AP classes are:

apstring (string data type)


apvector (improved one-dimensional array)
apmatrix (improved two-dimensional array)
apstack (to be introduced later)
apqueue (to be introduced later)

Use of the AP classes requires that the necessary files are


positioned in a place where C++ will look during compile time.

The AP classes are a good example that it is possible, and desirable to use the
tools provided by C++ and make our own better tools. In all honesty, the average
student probably did not think that there was much difference between any of the
C++ data types and the AP classes. From your point of view any C++ data type
could be used no matter what, and the AP classes required inclusion of certain
files in an appropriate directory.

If you prefer to think of the AP classes as C++ data structures, go right ahead.
You did not create them. At the same time you have been looking rather closely
at some of the AP classes in the last couple of chapters, and soon you will be quite
familiar with the apstack and apqueue classes.

Abstract Data Type (ADT)

An abstract data type (ADT) is a data type with a set


of data and a set of functions that can manipulate the data.
The ADT specifies what kind of data can be stored,

Chapter XXXIV Introduction to Data Abstraction 34.7


and how the data can be manipulated by the functions.
However, the implementation of an ADT in a specific
programming language is not part of the ADT definition.

You probably think that this is another goofy Schram definition. It probably
looks like a crossing between a data structure definition and an object definition
to you. We have not reviewed the object definition yet, but that ADT has the
distinct smell of attributes (data) and actions (functions) that OOP has been
blasting at you for many chapters. At the same time, it has some of the data
structure flavor as well. The ADT definition has two very important components.
The first component states that an ADT has data and functions that act on the
data. At that stage it sure sounds like a data structure. Now there comes a later
component that says that the implementation of the ADT is not part of any ADT
definition.

This means that I can talk about a data type, called CardDeck. Before I even
worry about how to store data, and how to manipulate the data, I sit down and do
some thinking. This data type is needed for a program to play Blackjack. I need
to store cards and those cards need to be shuffled, dealt, counted, etc. At this
stage I am thinking about the data type in an abstract manner. Whether an array, a
record, a class, whatever is used to implement this data type is not a concern right
now. At the abstract data type stage, implementation is not an issue.

You are getting somewhat suspicious. The CardDeck is used as an example to


explain an ADT, and you have excellent recall that the CardDeck class was a
frequent visitor in an variety of object oriented programming chapters. There
seems to be some strong relationship between an ADT and an object.

Object Definition

An object is an abstract data type (ADT) which provides the


capabilities of encapsulation, inheritance and polymorphism.

The relationship between an ADT and an object is so strong that an ADT can be
used to define an object. Objects have abstract data type written all over it. The
key difference is that an object goes further and also includes inheritance and
polymorphism. You may think that I left out encapsulation but that was quite
intentional. What is encapsulation? Is it not packaging both the attributes (data)
and actions (member functions) in the same data type. It sure sounds like the
definition of an ADT to me.

Chapter XXXIV Introduction to Data Abstraction 34.8


You may have another concern. Many chapters have been devoted to OOP. You
are getting ready to do some serious work with ADTs. So ADTs follows OOP,
and now you learn that an object is an ADT. Are we doing this backwards? The
problem is due to the fact that computer science is rarely taught in a pure
sequential manner. There is a tendency to bounce back and forth with similar
topics and introduce additional information at each stage. When objects were first
introduced, we did not talk about data types that performed certain actions
without worrying about implementations. At that early stage we were too heavily
concerned about the syntax level. Now, the roles have reversed and syntax will
take a back seat. Yes, syntax is still important since you cannot test your program
logic without a working program. On the other hand, the majority of C++ syntax
has been introduced at this stage, and we now have the luxury to focus more on
computer science topics, such as abstract data structures.

34.3 Information Hiding

The information hiding topic is not new, but it belongs in this chapter. Data
abstraction and information go hand in hand. Besides, what do you expect from a
book that is titled Exposure.

Information Hiding Definition

Information Hiding is the concept of thinking about


programming features and using programming features
without concern, or even knowledge about the implementation
of such features.

The definition of information hiding shares the implementation phrase of the


ADT definition. Every single human being functions, every day, in some
capacity of information hiding. Consider the following silly story about starting a
car.

OK, I put the key in the ignition and turn the key. This will complete an electronic
circuit and activate the starter motor. As the starter motor turns the engine over,
the following process brings the car in motion. Fuel is pumped from the tank to
the fuel injectors. The fuel injectors convert the liquid gas to a fine spray and

Chapter XXXIV Introduction to Data Abstraction 34.9


inject this spray inside the chambers of each cylinder. The turning of the engine
moves the pistons upward inside the chambers and it compresses the gas into a
tight space. With perfect timing the rotor, inside the distributor, completes an
electric circuit that sends an electric pulse to the appropriate cylinder. The
electric pulse is passed through a spark plug that protrudes inside the cylinder
and a small spark is emitted in the chamber. The compressed gas is ignited by the
spark and explodes. The explosion causes instant expansion and the piston is
driven downward in the cylinder. The piston head is connected to a piston rod
which moves up and down. The up and down motion of the piston rod from the
repeated explosions is converted to a circular motion. This circular motion is
than transferred to the crankshaft. The crankshaft continues the energy path to
the transmission. The transmission then selects the appropriate gear for the car
movement. From the transmission the turning force goes by drive shaft and
various universal joints to the differential. The differential distributes the turning
force to the wheels and the car starts to move.

Is it necessary for you to know all those car details before you drive a car? No it
is not necessary. Furthermore, as much detail as I wrote about car functionality,
you can count on many details that are left out. Details that I never knew, and it
simply does not matter. A car is a classic example of an object. It contains
attributes and actions, and you can activate the car actions without knowing how
such actions are implemented.

Reasons for Information Hiding

 There can be valid economic reasons.


 Implementation details may be too complex and
too difficult to understand
 It allows focus on a new and different topic without
concern about prior details.

There can be valid economic reasons.

Suppose that you have a large program team working on a new software
application. When your product is finished, you eagerly market and sell the
product to anybody interested in buying it. What do the customers get? They get
an executable file of your software application and all the necessary files to run
the program. Your customers do not get any of the source code. The majority of
customers would not be interested in the source code and the few people who are
interested in the source code could duplicate your product and compete in an

Chapter XXXIV Introduction to Data Abstraction 34.10


unfair manner without much effort. You may argue that a competitor can simply
copy your distribution files and sell them as well. That is true, but it can be easily
proven that such sales are copies of a copyrighted product. On the other hand,
you may have created a really revolutionary approach to solving a certain
problem. This new tool can be used in different applications as well. A
competitor can use the source code and use it in a different package. In such a
scenario it becomes more difficult to prove that the competitor stole your
research.

Implementation details may be too complex and too


difficult to understand.
The graphics file includes a Circle function. This function is implemented with
trigonometric concepts. Do you understand trigonometry? Some students do, and
some students do not. There are also rotating three-dimensional cubes that
involve mathematical formulas that will challenge all but the most mathematically
talented students. The point is that you can function very nicely without the
knowledge of such complexity. You happen to be writing a program that will
display a snowman. You need circles, and trigonometry is not your concern.

Chapter XXXIV Introduction to Data Abstraction 34.11


It allows focus on a new and different topics
without
concern about prior details.
Most students can really understand the first two reasons for information hiding.
It is with this third reason that there are problems. You can call it a letting go sort
of problem. Consider the following situation: You want to create a video game,
and this video game requires a large number of small characters that bounce on
the screen. After various approaches to creating your video characters, you give
up and decide that you need a special graphics editor, or icon editor to assist you
in this part of the program.

At this point the focus is completely on the icon editor. You design it, write it,
test it and then use it for your graphics game. It is precisely at this point that the
fully tested icon editor is used to create some graphics sprites. You are no longer
concerned about the implementation of the icon editor. That part is done now and
focus switches.

I am personally completely convinced that many students have difficulty


developing large programs because of information hiding. They do not let go and
keep too many details floating around at the same time. It is true that some
people can handle a much larger quantity of details than other people. It really
does not matter because everybody has a mental focus limit. Information hiding
is your friend. It helps you to maintain sanity.

34.4 An ADT Free Response Example

You can pretty well tell that data abstraction is a big deal. It has been
mentioned earlier, and the topic keeps returning. Right now there is an entire
chapter devoted to this abstraction business. It is wise to take data abstraction
seriously. It is an important topic in computer science and the committee who
creates the AP Computer Science Examination enjoy including ADT questions on
the exam.

The whole idea of ADT questions is to test a student’s ability to create new
routines with the aid of existing routines. You are in actuality programming at a

Chapter XXXIV Introduction to Data Abstraction 34.12


higher level than you normally would. This approach is in the spirit of data
abstraction and also very much in the spirit of object oriented programming.
The example that follows can be considered a typical ADT free response
question. String manipulation is a popular choice for ADT questions. The main
point to remember is that you are adding additional functionality to a data type
without directly accessing the storage of the data type. All you use are the
available functions. This probably sounds just like using the public segment of a
class without touching the private segment. Object oriented programming does an
excellent job enforcing the point of data abstraction. The example that follows
does not use object oriented programming, but it uses data abstraction very much.

String ADT Free Response Question Example

For this problem, you will write two functions that use the apstring class to
represent strings. The details of the apstring class implementation is not known to
you. However, apstring can be manipulated with a large variety of functions. In
particular, for this problem you will need three functions, whose headers and
descriptions follow below:

int length( ) const;


// postcondition: returns # of chars in apstring
object

apstring operator + ( const string & lhs, const string


& rhs )
// postcondition: returns concatenation of lhs with
rhs

apstring substr( int pos, int len ) const;


// description: returns the substring of length len
at pos
// precondition: this string represents c0, c1, ...,
c(n-1)
// 0 <= pos <= pos + len - 1 < n.
// postcondition: returns the string that represents
// c(pos), c(pos+1), ..., c(pos+len-1)

(a) Write function DeleteString that reduces a nonempty string S by Count


characters, starting at the character position indicated by Start.

For example:

Chapter XXXIV Introduction to Data Abstraction 34.13


String S before the call DeleteString(S,4,2);

S A T U R D A Y

String S after the call DeleteString(S,4,2);

S A T D A Y

In writing function DeleteString you may only manipulate strings by using calls
to functions subtr, length and operator+.

Complete function DeleteString below the following header:

void DeleteString(apstring &S, int Start, int Count)


// precondition: S = a1a2...an
// postcondition: S = a1...aStart-1aStart+Count...an

(b) Write function InsertString that alters a nonempty string, S1, by inserting
a nonempty string, S2, starting at the character position indicated by Start.

For example:

String S1 and S2 before the call InsertString(S1,S2,6);

S1
S A T U R D A Y
S2
F U N

String S1 and S2 after the call InsertString(S1,S2,6);

S1
S A T U R F U N D A Y
S2
F U N

Chapter XXXIV Introduction to Data Abstraction 34.14


In writing function InsertString you may only manipulate strings by using calls
to functions subtr, length and operator+.

Complete function InsertString below the following header:

void InsertString(apstring &S1, apstring &S2, int


Start)
// precondition: S1 = a1a2...an
// S2 = b1b2...bn
// postcondition: S1 = a1...aStart-1b1b2..bmaStart+Count...an

The two solution functions of this free response question do not involve any
source code knowledge of the apstring class. This is the whole point of working
with data abstraction. You are expected to create new tools with the use of
existing tools. You are not expected to create tools from scratch.

Do not flip the page right away. The solutions are shown there and motivated
student that you are, you want to get out a piece of paper and see if you can write
the solution without any help.

DeleteString Solution Function

void DeleteString(apstring &S, int Start, int Count)


{
apstring T1, T2;
T1 = S.substr(0,Start-1);
T2 = S.substr(Start+Count-1,S.length()-(Start+Count-
1));
S = T1 + T2;
}

InsertString Solution Function

void InsertString(apstring &S1, apstring &S2, int


Start)
{
apstring T1, T2;

Chapter XXXIV Introduction to Data Abstraction 34.15


T1 = S1.substr(0,Start-1);
T2 = S1.substr(Start-1,S1.length()-Start+1);
S1 = T1 + S2;
S1 = S1 + T2;
}

You may not may not accept the two solutions. Perhaps you can trace through the
code and see that the code is correct. At this stage you should be able to do that
type of tracing. Just to be sure, I am including two programs that will test each
one of the functions.

// PROG3401.CPP
// This program demonstrates how to use data
abstraction by
// creating a new DeleteString function using existing
function
// without knowing the implementation of the new
functions.

#include <iostream.h>
#include <conio.h>
#include "APSTRING.H"

void DeleteString(apstring &S, int Start, int Count)


{
apstring T1, T2;
T1 = S.substr(0,Start-1);
T2 = S.substr(Start+Count-1,S.length()-(Start+Count-
1));
S = T1 + T2;
}

void main()
{
apstring String1 = "SATURDAY";
apstring String2 = "GOOD MORNING";
apstring String3 = "HELLO";
clrscr();

Chapter XXXIV Introduction to Data Abstraction 34.16


DeleteString(String1,4,2);
cout << String1 << endl;
DeleteString(String2,12,1);
cout << String2 << endl;
DeleteString(String3,1,1);
cout << String3 << endl;
getch();
}

PROG3401.CPP OUTPUT

SATDAY
GOOD MORNIN
ELLO

The DeleteString function does a nice job. Notice the manner in which the
function is tested. Three different kinds of strings are removed. The first string is
from the middle, the second string from the end, and last test is a string removed
from the front of the string. Is this a complete test of the function? Can you think
of test situations that were not considered in this program?

// PROG3402.CPP
// This program demonstrates how to use data
abstraction by
// creating a new InsertString function using existing
function
// without knowing the implementation of the new
functions.

#include <iostream.h>
#include <conio.h>
#include "APSTRING.H"

void InsertString(apstring &S1, apstring &S2, int


Start)
{
apstring T1, T2;
T1 = S1.substr(0,Start-1);

Chapter XXXIV Introduction to Data Abstraction 34.17


T2 = S1.substr(Start-1,S1.length()-Start+1);
S1 = T1 + S2;
S1 = S1 + T2;
}

void main()
{
apstring String2 = "GOOFY";
apstring String1 = "SATURDAY";
clrscr();
InsertString(String1,String2,6);
cout << String1 << endl;
String1 = "SATURDAY";
InsertString(String1,String2,1);
cout << String1 << endl;
String1 = "SATURDAY";
InsertString(String1,String2,9);
cout << String1 << endl;
getch();
}

PROG3402.CPP OUTPUT

SATURGOOFYDAY
GOOFYSATURDAY
SATURDAYGOOFY

34.5 Data Abstraction and Objects

You learned in the previous section how new functions can be created with the
help of existing functions. Furthermore, it is possible to create new functionality

Chapter XXXIV Introduction to Data Abstraction 34.18


without knowing any of the implementation details of the functions that are used
to write new functions. The capability of the new functions is used and it is not
necessary to poke into any source code details. Do not sweat the implementation
is the theme song of data abstraction and the last section demonstrated the
principle quite nicely.

At the same time, you may have been surprised that data abstraction was
demonstrated without using any objects. The definition of an object, shown a few
pages back, states that an object is an ADT. This certainly makes objects
excellent examples for data abstraction programs. Do not worry, because this
section will demonstrate data abstraction with the aid of two classes.

Turtle Graphics

In the eighties many students learned to create graphics images with the help of a
special turtle graphics package. The programming language Logo used such
graphics and it was an excellent approach in creating simple graphics images.
Data abstraction with objects will be shown with the aid of a Turtle class. This
class will be demonstrated in program PROG3403.CPP. Now this program will
not demonstrate data abstraction with objects yet. First, we must set the stage and
the stage is going to be set with a very simple graphics class, called Turtle.

The Turtle class actually draws its “graphics” images in text with pound signs.
This is done to make sure that the program example will execute on any computer
system with any compiler. The concepts of turtle graphics is the same and you
just need to imagine a fancier pixel graphics display. The concepts of turtle
graphics is to move a “turtle” on the screen. Once upon a time it did look like a
turtle. In our program the turtle is our cursor. The object is to move the turtle
around with a variety of commands to manipulate some image. The command
descriptions of the Turtle functions are shown before the actual program
example.

Turtle Class Member Functions


void PenUp()
// cursor can move to new location without drawing a
line

void PenDown()
// cursor can move to a new location and will draw a
line

Chapter XXXIV Introduction to Data Abstraction 34.19


int GetX() const
// returns the current X position

int GetY() const


// returns the current Y position

void Change(Direction P)
// Changes the direction of the moving cursor. There
are
// four directions: UP, DOWN, LEFT, RIGHT. The four
// directions are enumerated constant to be used as
parameters.

void Move(int Distance)


// Move the cursor Distance spaces in the current
direction
// Pound signs are drawn when PenDown function is
called

Program PROG3403.CPP draws a square first, skips a distance with the pen up,
and then draws a line. Horizontal distances are intentionally doubled to make the
horizontal and vertical distance give approximately the same length.

// PROG3403.CPP
// This program draws a square and a line with the Turtle class.

#include <iostream.h>
#include <conio.h>
#include <dos.h>
#include "BOOL.H"

enum Direction {UP,DOWN,LEFT,RIGHT};

class Turtle
{
private:
int XPos;
int YPos;
bool Show;
Direction Point;
public:
Turtle() { XPos = 40; YPos = 12; Show = true; Point = UP; }
void PenUp() { Show = false; }
void PenDown() { Show = true; }
int GetX() const { return XPos; }
int GetY() const { return YPos; }
void Change(Direction P) { Point = P; }
void Move(int Distance);
};

Chapter XXXIV Introduction to Data Abstraction 34.20


void Turtle::Move(int Distance)
{
int K;
for (K=1; K <= Distance; K++)
{
switch (Point)
{
case UP:
YPos--; break;
case DOWN:
YPos++; break;
case LEFT:
XPos--; break;
case RIGHT:
XPos++; break;
}
gotoxy(XPos,YPos);
if (Show) cout << "#";
delay(50);
}
}

void main()
{
clrscr();
Turtle T;
T.PenDown();
T.Move(5);
T.Change(RIGHT);
T.Move(9);
T.Change(DOWN);
T.Move(4);
T.Change(LEFT);
T.Move(9);
T.PenUp();
T.Move(5);
T.PenDown();
T.Move(10);
getch();
}
PROG3403.CPP OUTPUT

##########
# #
# #
# #
######### ##########

Chapter XXXIV Introduction to Data Abstraction 34.21


The previous program succeeded in drawing a square, but it was quite tedious.
The Move function and the Change function had to be used frequently and the
whole process seemed too involved. It needs to be possible to call some simple
Square or Rectangle command, just as you have used with some previous
graphics programs.

There exist several options for us right now. Every time we need a square or
rectangle, we can use the existing commands. That option is undesirable because
there are just too many commands. We can also expand the Turtle class and add
a Square member function. Finally, we can make Turtle a base class and then
derive a class, Turtle2 that will implement a Square function.

I have selected the last option. It seems to be truly in the spirit of data abstraction.
In this situation we are declaring a new class, Turtle2, and derive it from the
Turtle base class. We now have all the functionality of the Turtle class and in
proper data abstraction style, we have no clue about any of the Turtle details.
This allows us to create a Square member function for our current needs. This
process is shown in program PROG3404.CPP, which draws a single square, and
the main function shows that it is considerably less work.

Using Enumerated Types

The program examples in this section use


enum Direction {UP,DOWN,LEFT,RIGHT};
The use of an enumerated type is done strictly for program
readability. It is not a data abstraction requirement.

// PROG3404.CPP
// This program demonstrates abstraction by creating a
second
// Turtle class without any source code of the base
Turtle class.

#include <iostream.h>
#include <conio.h>
#include <dos.h>
#include "BOOL.H"

enum Direction {UP,DOWN,LEFT,RIGHT};

Chapter XXXIV Introduction to Data Abstraction 34.22


class Turtle
{
private:
int XPos;
int YPos;
bool Show;
Direction Point;
public:
Turtle() { XPos = 40; YPos = 12; Show = true;
Point = UP; }
void PenUp() { Show = false; }
void PenDown() { Show = true; }
int GetX() const { return XPos; }
int GetY() const { return YPos; }
void Change(Direction P) { Point = P; }
void Move(int Distance);
};

class Turtle2 : Turtle


{
public:
void Square(int Size);
};

void Turtle2::Square(int Size)


{
PenDown();
Change(RIGHT);
Move(2*Size-1);
Change(DOWN);
Move(Size-1);
Change(LEFT);
Move(2*Size-1);
Change(UP);
Move(Size-1);
}

void main()
{
clrscr();
Turtle2 T;
T.Square(5);

Chapter XXXIV Introduction to Data Abstraction 34.23


getch();
}

void Turtle::Move(int Distance)


{
int K;
for (K=1; K <= Distance; K++)
{
switch (Point)
{
case UP:
YPos--; break;
case DOWN:
YPos++; break;
case LEFT:
XPos--; break;
case RIGHT:
XPos++; break;
}
gotoxy(XPos,YPos);
if (Show) cout << "#";
delay(50);
}
}

PROG3404.CPP OUTPUT

##########
# #
# #
# #
##########

There are bunches more that can be said about data abstraction, information
hiding and all this good program design stuff in a proper manner. Such a topic

Chapter XXXIV Introduction to Data Abstraction 34.24


rapidly becomes duller than dirt and loses it effectiveness. In the chapters to
come you will repeatedly see examples of data abstraction, and it is in the actual
use of a concept that you get to appreciate the practical value.

If you are not convinced that data abstraction and information hiding are
important, fine. Just promise that you will keep an open mind and look closely at
the programs that will follow. Hopefully, you will be a convert by the time that
this book is finished.

Chapter XXXIV Introduction to Data Abstraction 34.25

You might also like