/
chap_classes.tex
406 lines (321 loc) · 17.1 KB
/
chap_classes.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
% This work by Jeremy A. Hansen is licensed under a Creative Commons
% Attribution-NonCommercial-ShareAlike 3.0 Unported License,
% as described at http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode
%Abstract Data Types
Imagine for a second you're behind the wheel of an automobile.
You're driving along, but do you know your engine is working right if it's not making any horrendous screeching sounds?
Do you have any idea how your steering actually works when you turn the wheel?
So long as you can press down on the accelerator to move forward and the steering handles correctly, you probably don't care about the specifics of how things work.
\Keyword{Abstract data types} (ADTs) are the automobiles of C++, and one of the reasons C++ is known as an \Keyword{object-oriented programming language}.
It's their job to package and obscure the information from the average user, and at the same time make their lives more convenient.
ADTs can be thought of as a group of data of different types that are treated as a single item.
For example, if we wanted to record the name, identification number, age, graduation date, and sex of all of the students on a campus, we could create a new data type named \Code{Student} with those variables.
In the following sections we will show you how to use and define two types of ADTs: structures and classes.
\LevelD{\Code{struct}s}
A common example of a \Code{struct} is a \Code{Point}. \Code{Point}s store \Code{int}, \Code{float}, or \Code{double} variables \Code{x} and \Code{y}, which represent the position of the \Code{Point} on the the X and Y axes on a coordinate plane.
Such a \Code{struct} might look like this: \nopagebreak[4]
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
struct Point
{
double x;
double y;
};
\end{lstlisting}\end{minipage}
In the example, the keyword \Code{struct} is used to declare the structure definition while the identifier, the word directly to the right of struct (\Code{Point}), is the structure name and the name of a new data type.
The braces are used just like when we define a function.
However, directly after the closing brace, there must be a semicolon!
Once a structure is defined, it can be used just like the data types \Code{int}, \Code{char}, \Code{string}, and so on.
For example, we might declare a \Code{Point} structure named \Code{input} like this:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
Point input;
\end{lstlisting}\end{minipage}
\LevelD{Assigning values to member variables}
Any variable of type \Code{Point} such as the one above is a collection of two variables, \Code{x} and \Code{y}.
Any variables contained in the \Code{struct} can be accessed by combining the structure name---\Code{input} in our example---followed by a symbol called the \Keyword{dot operator} (the period, \Code{.}) and the member variable's name.
For example, if we wanted to set \Code{x} in \Code{input}, we would use the dot operator as follows:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
input.x = 5;
\end{lstlisting}\end{minipage}
%\LevelD{Initializing member variables}
% TODO: Add more here
%\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
%Point input(3, 6);
%\end{lstlisting}\end{minipage}
\LevelD{Classes}
\Code{class}es are like \Code{struct}s except \Code{class}es contain both variables and functions, whereas \Code{struct}s only contain variables.\footnote{This has been the conventional way to think about \Code{class}es and \Code{struct}s, but in reality the \emph{only} difference between the two is that members of a \Code{struct} are public by default and members of a \Code{class} are private by default.}
Also, in a \Code{struct}, member variables are public by default while all members of a \Code{class} are private by default.
We'll discuss the distinction more in a minute.
First, let's take a look at an actual \Code{class} definition.
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
class Rectangle
{
public:
Rectangle(); //A default constructor
//The following two lines are mutators
void setBase(float length);
void setHeight(float length);
//The following two lines are accessors
float getHeight();
float getBase();
//The following two lines perform operations
float findArea();
float findPerimeter();
private:
float Base;
float Height;
};
\end{lstlisting}\end{minipage}
Notice the similar syntax to the \Code{struct}.
Like a \Code{struct}, the declaration starts with the \Code{class} keyword, followed by the name of the \Code{class}, and after the closing right brace, a semicolon.
Notice the \Code{public:} and \Code{private:} sections of the definition.
To indicate that a set of member variables or functions is private, we use the \Code{private} keyword followed by a colon.
Everything after the keyword will be considered private.
We will discuss what this means in the next section.
On the other hand, if we want to indicate that a set a member variables or functions is public, we use the keyword \Code{public} followed by a colon.
Everything after this keyword will be considered public.
\LevelD{\Code{public} and \Code{private} variables and functions}
The biggest difference between \Code{class}es and \Code{struct}s is the ability to determine how accessible the data within the class is.
A general rule of thumb is to put variables in the \Code{private:} section, where they would be referred to as private member variables, and related functions in the \Code{public:} section, where they would be referred to as public member functions.
Private members can only be accessed by the \Code{class}'s member functions and nowhere else, while public members can be used anywhere, in the same way that the members of a \Code{struct} can be used.
Within the above \Code{class} definition, we have seven member functions that we need to define.
Each function has a specific purpose to set the values of private member variables, return the values of private member variables, or perform some other operation using those member variables.
Functions that are declared in the above code with names starting with the word \Code{get} will be used to access the variables; these functions are called \Keyword{accessors}.
Functions that are declared in the above code that have names starting with the word \Code{set} will be used to change the variables' values; these functions are called \Keyword{mutators}.
Accessors and mutators can be named whatever you like, but it is a common convention to name them \Code{get} and \Code{set} plus the name of the variable you are accessing or mutating.
The functions whose names start with \Code{find} perform operations using the variables, but do not change them or return their values directly.
The function named \Code{Rectangle()} is known as a \Keyword{constructor}.
When a \Code{Rectangle} object is created, it will be initialized according to the code in this constructor.
By the end of this chapter, you'll understand how useful these are in object-oriented programming.
\LevelD{Defining member functions}
We now describe how to use member functions with \Code{private} member variables.
When we define a member function, all the member variables within the class are accessible to the function.
For example, we can define the member function \Code{setBase()} from \Code{Rectangle} above like this:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
void Rectangle::setBase(float length)
{
Base = length;
}
\end{lstlisting}\end{minipage}
In this code, we are able to directly access the member variable \Code{Base} because both the function \Code{setBase()} and the member variable \Code{Base} are a part of the \Code{class}.
Since we are not returning anything to the user, the function is defined as a \Code{void} function.
In order to define a member function, we have to use a special operator called the \Keyword{scope resolution operator} (\Code{::}).
The function is defined by using the return type, the class name, scope resolution operator, then the member function name with any parameters listed just like any other non-class function.
\LevelD{Using member functions}
All member functions have direct access to member variables even if the variable is private.
The reason we use mutators is because we do not want the user to have direct access to any variables within the class---we give them indirect access instead.
We do this by requiring them to pass a value to the mutator member function which sets the member variable.
That might look like this:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
int main()
{
Rectangle r;
float b;
cout << "Please input the length of the base: ";
cin >> b;
r.setBase(b);
return 0;
}
\end{lstlisting}\end{minipage}
In the above code, we start by creating a \Code{Rectangle} variable named \Code{r}.
After the user is prompted for the length of the base, which is stored in the variable \Code{b}, we call the \Code{setBase()} member function with the dot operator and pass \Code{b} as a parameter to the function.
We are able to pass the value of the variable entered by the user to the \Code{setBase()} function which then sets the member variable \Code{Base} to the passed value.
This is how we ``mutate'' private member variables in a \Code{class} using a public member function.
To retrieve the value of a member variable, we need to create accessor functions.
These are defined like this:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
float Rectangle::getBase()
{
return Base;
}
\end{lstlisting}\end{minipage}
When it comes to using accessors, it is very simple.
Just match the data type that you want to access, in this case it was a \Code{float}, and define the member function with that return type.
Then, in order to access the variable, all we need to do is use the keyword \Code{return} followed by the identifier.
This enables us to access the private variable when we need to.
\LevelD{\Code{class}es and \Code{struct}s together}
We can also combine \Code{struct}s and \Code{class}es if need be.
For example, if we wanted to take in three points we could create a \Code{Triangle} class with these points which are individually of type \Code{Point}, a \Code{struct} that contains \Code{x} and \Code{y} variables:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
struct Point
{
double x;
double y;
};
class Triangle
{
public:
// accessors for points a, b, and c
// mutators for points a, b, and c
private:
Point a;
Point b;
Point c;
};
\end{lstlisting}\end{minipage}
Here we have the ability to combine a \Code{struct} with a \Code{class} in order to have all three points, \Code{a}, \Code{b}, and \Code{c} that each contain their own variables \Code{x} and \Code{y}.
Despite the fact that the variables in the \Code{struct} are public, we cannot access those specific values outside the \Code{Triangle} unless we use a member function.
This is because they're still private members of the class \Code{Triangle}, so their scope is limited to functions within the class.
If we had a mutator function for \Code{Point a}, it might look like this:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
void Triangle::setA(double userX, double userY)
{
a.x = userX;
a.y = userY;
}
\end{lstlisting}\end{minipage}
The values of \Code{userX} and \Code{userY} are passed in by the calling function.
Notice again that in order to access the \Code{x} and \Code{y} coordinates, we must use the dot operator with any of the \Code{Point} objects \Code{a}, \Code{b}, or \Code{c}.
\LevelD{Constructors}
% TODO: This section was initially named ``Constructors and Destructors'' -- we should probably include destructors at some point
Another way to set the values of the variables in a class is through constructors.
A \Keyword{constructor} is a member function with the same name as the class and cannot be called directly.
Constructors are what we use to initialize the variables of the class when it's first created.
For example, if we wanted to set default values for a class named \Code{student} defined as: \nopagebreak[4]
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
class student
{
public:
student(); // constructor
//accessors
//mutators
private:
string name;
int age;
int grad_year;
string id;
};
\end{lstlisting}\end{minipage}
\noindent we would have a default constructor with the name \Code{student()} without any return type.
To initialize the variables in the class through the constructor, we use syntax similar to a function definition:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
student::student()
{
name = "N/A";
age = 0;
grad_year = 0;
id = "A00000000";
}
\end{lstlisting}\end{minipage}
\LevelD{Overloading Member Functions}
Note that, like other functions, you can overload any of the functions in a class.
Going back to the \Code{Rectangle} example used earlier, take a look at the following code.
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
class Rectangle
{
public:
Rectangle(); //A default constructor
//Overloaded constructor
Rectangle(float userBase, float userHeight);
void setBase(float length); //These two lines are mutators
void setHeight(float length);
float getHeight(); //These two lines are accessors
float getBase();
float findArea(); //These two lines perform operations
float findPerimeter();
private:
float Base;
float Height;
};
\end{lstlisting}\end{minipage}
Notice the second constructor, \Code{Rectangle(float userBase, float userHeight)}.
We define it very similarly to the default constructor:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
Rectangle::Rectangle(float userBase, float userHeight)
{
Base = userBase;
Height = userHeight;
}
\end{lstlisting}\end{minipage}
\LevelD{Review Questions}
\begin{enumerate}
\item Given the following \Code{struct} definition and global variable:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
struct personInfo
{
string name;
int birth_year;
int birth_month;
int birth_day;
int age;
};
personInfo pinfo;
\end{lstlisting}\end{minipage}
\noindent which of the following are incorrect ways to use the dot operator?
\begin{enumerate}
\item \Code{pinfo.age}
\item \Code{personInfo.birth\_year}
\item \Code{information.name}
\item \Code{pinfo.(string name)}
\item \Code{birth\_year.pinfo}
\end{enumerate}
\begin{comment}
% TODO: We don't cover initialization yet.
\item Consider the following \Code{struct}:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
struct personInfo
{
string name;
int birth_year;
string birth_month;
int birth_day;
int age;
};
\end{lstlisting}\end{minipage}
Which of the following is the correct way to initialize the variables from the \Code{struct} above?
\begin{enumerate}
\item {\tiny \Code{personInfo info = \{"Michael", 1996, 3, 24, "sixteen"\};}}
\item {\tiny \Code{personInfo info = \{"Michael", 1996, March, 24, 16\};} }
\item {\tiny \Code{personInfo info = \{"Michael", 1996, "March", 24, 16\};}}
\item {\tiny \Code{struct info = \{"Michael", 1996, "March", 24, 16\};} }
\end{enumerate}
\end{comment}
\item Create a \Code{class} called \Code{Animal} that can store information about animals in a zoo and has the following private variables: \nopagebreak[4]
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
string name; // the name of the animal
int pounds; // number of pounds of food eaten
char animalType; // the type of animal:
// 'h' for herbivore
// 'c' for carnivore
\end{lstlisting}\end{minipage}
You should have public member functions that get and set each variable, and a function called \texttt{print()} that prints all the information about the animal.
\item This program will require a \Code{struct} and a \Code{class}.
Write a program that can calculate the slope of a line.
You will have a \Code{struct} called \Code{Point} which contain the following variables:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
double x, y;
\end{lstlisting}\end{minipage}
You will then have a class called \Code{Line}, and it will have the following private variables:
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
Point a, b;
\end{lstlisting}\end{minipage}
Your class should have accessor and mutator functions, a function that calculates and returns the slope of a line between the two \Code{Point}s as a \Code{double}, and a function that outputs the data to the user called \Code{print()}.
\end{enumerate}
\LevelD{Review Answers}
\begin{enumerate}
\item Only (a) is correct: (b) through (e) will result in syntax errors.
\item
\noindent\begin{minipage}{\linewidth}\begin{lstlisting}
class Animal
{
public:
Animal();
string getName();
void setName(string inputName);
int getPounds();
void setPounds(int inputPounds);
char getType();
void setType(char inputType);
void print();
private:
string name ; // the name of the animal
int pounds ; // number of pounds of food eaten
char animalType ; // the type of animal
};
\end{lstlisting}\end{minipage}
\end{enumerate}
\LevelD{Further Reading}
\begin{itemize}
\item \url{http://pages.cpsc.ucalgary.ca/~jacob/Courses/Fall00/CPSC231/Slides/08-Arithmetic.pdf}
\item \url{http://www.tutorialspoint.com/cplusplus/cpp_classes_objects.htm}
\item \url{http://www.cprogramming.com/tutorial/lesson7.html}
\end{itemize}