c++ classes and data structures jeffrey s. childs chapter 1 structs and classes
DESCRIPTION
C++ Classes and Data Structures ppt Ch1TRANSCRIPT
C++ Classes and Data StructuresJeffrey S. Childs
Chapter 1Structs and Classes
1
Jeffrey S. Childs
Clarion University of PA
© 2008, Prentice Hall
Structs
• A struct holds data, like an array• Each unit of data in a struct is called a data
member (or member)– they are called “elements” in arrays
• In a struct, each data member can have a different data type– in arrays, the data type of each element is the
same
2
Example Using a Struct
3
1 #include <iostream>2 #include <iomanip>3 #include <string>45 using namespace std;67 struct CarType {8 string maker;9 int year;10 float price;11 };1213 void getYourCar( CarType & car );14
Don’t forget this semicolon.
Example Using a Struct (cont.)
4
15 int main( )16 {17 CarType myCar, yourCar;1819 myCar.maker = "Mercedes"; // I wish20 myCar.year = 2005;21 myCar.price = 45567.75;22
Example Using a Struct (cont.)
5
23 getYourCar( yourCar );2425 cout << "Your car is a: " <<
yourCar.maker << endl;26 cout << fixed << showpoint <<
setprecision( 2 ) << 27 "I'll offer $" << yourCar.price - 100
<< 28 " for your car." << endl;2930 return 0;31 }32
Example Using a Struct (cont.)
6
33 void getYourCar( CarType & car )34 {35 cout << "Enter your maker: ";36 cin >> car.maker;37 cout << "Enter the year: ";38 cin >> car.year;39 cout << "Enter the price: $";40 cin >> car.price;41 }
Object Assignment
• An object of a struct can be assigned to another object of the same struct type:
myCar = yourCar;
• This assigns each data member in yourCar to the corresponding data member of myCar
• Also assigns any array data members
7
Classes
• A class is similar to a struct• A class contains data members, but it also contains
function members• Objects are made from classes, similarly to the way
that objects are made from structs• The main program communicates with the objects
– data is passed from main program to object and from object back to the main program
8
Main Program Using Objects
9
Object A
Object B
Object C
Main
Program
Main Program Using Objects
10
Object A
Object B
Object C
Main
Program
Main Program Using Objects
11
Object A
Object B
Object C
Main
Program
Main Program Using Objects
12
Object A
Object B
Object C
Main
Program
Main Program Using Objects
13
Object A
Object B
Object C
Main
Program
How the Main ProgramUses A Class Object
• The main program does not access the data within a class object
• The main program only accesses the functions of a class object– communication occurs by passing data as
parameters into the object’s function– the object passes data to the main program
through its return type
14
Main Program and Object
15
Main
Program
Object
public:
functions
private:
data
Main Program Calls a Function in the Object
16
Main
Program
Object
public:
functions
private:
data
The Function Accesses Data
17
Main
Program
Object
public:
functions
private:
data
Function Returns a Value Back to the Main Program
18
Main
Program
Object
public:
functions
private:
data
Main Program Calls a Different Function
19
Main
Program
Object
public:
functions
private:
data
Function Calls Another Function
20
Main
Program
Object
public:
functions
private:
data
Second Function Accesses Data
21
Main
Program
Object
public:
functions
private:
data
Second Function Returns Back to First Function
22
Main
Program
Object
public:
functions
private:
data
First Function Accesses Data
23
Main
Program
Object
public:
functions
private:
data
Function Returns Back to Main Program
24
Main
Program
Object
public:
functions
private:
data
Example of a Class
25
1 class Checkbook2 {3 public:4 void setBalance( float amount );5 bool writeCheck( float amount ); 6 void deposit( float amount );7 float getBalance( );8 float getLastCheck( );9 float getLastDeposit( ); 10 private:11 float balance;12 float lastCheck;13 float lastDeposit;14 };
This class definition is placed into its own file, called the class specification file, named checkbook.h (by convention)
Example of a Class (cont.)
26
1 class Checkbook2 {3 public:4 void setBalance( float amount );5 bool writeCheck( float amount ); 6 void deposit( float amount );7 float getBalance( );8 float getLastCheck( );9 float getLastDeposit( ); 10 private:11 float balance;12 float lastCheck;13 float lastDeposit;14 };
The writeCheck function returns false if the amount of the check is greater than the balance; returns true otherwise.
Example of a Class (cont.)
27
1 class Checkbook2 {3 public:4 void setBalance( float amount );5 bool writeCheck( float amount ); 6 void deposit( float amount );7 float getBalance( );8 float getLastCheck( );9 float getLastDeposit( ); 10 private:11 float balance;12 float lastCheck;13 float lastDeposit;14 };
Don’t forget the semicolon.
Example of a Class (cont.)
28
15 #include “checkbook.h”1617 void Checkbook::setBalance( float amount )18 {19 balance = amount;20 } The function definitions are placed into a
separate file called the class implementation file. This file would be called checkbook.cpp (by convention).
Example of a Class (cont.)
29
15 #include “checkbook.h”1617 void Checkbook::setBalance( float amount )18 {19 balance = amount;20 }
The balance variable is declared in the private section of the class definition.
Example of a Class (cont.)
30
15 #include “checkbook.h”1617 void Checkbook::setBalance( float amount )18 {19 balance = amount;20 }
Special notation for class function definitions
Example of a Class (cont.)
31
21 bool Checkbook::writeCheck( float amount )22 {23 if ( amount > balance )24 return false;25 balance -= amount;26 lastCheck = amount;27 return true;28 }
Example of a Class (cont.)
32
29 void Checkbook::deposit( float amount )30 {31 balance += amount;32 lastDeposit = amount;33 }
Example of a Class (cont.)
33
34 float Checkbook::getBalance( ) 35 {36 return balance;37 }3839 float Checkbook::getLastCheck( )40 {41 return lastCheck;42 }
end of checkbook.cpp
A Program that Uses the “Checkbook” Class
34
1 #include <iostream>2 #include <iomanip>3 #include "checkbook.h"45 using namespace std;67 int menu( );89 const int CHECK = 1, DEPOSIT = 2, BALANCE = 3, QUIT = 4; 1011 int main( )
A main program that uses the "Checkbook" class is placed into a separate .cpp file
35
12 {13 Checkbook cb;14 float balance, amount;15 int choice;16 cout << "Enter the initial balance: $";17 cin >> balance;18 cb.setBalance( balance );1920 cout << fixed << showpoint << setprecision( 2 );
A Program that Uses the "Checkbook" Class (cont.)
36
21 choice = menu( );22 while ( choice != QUIT ) {23 if ( choice == CHECK ) {24 cout << "Enter check amount: $";25 cin >> amount;26 if ( cb.writeCheck( amount ) )27 cout << "Check accepted." << endl;28 else {
A Program that Uses the "Checkbook" Class (cont.)
37
29 cout << "Your balance is not high ";30 cout << "enough for that check." << endl; 31 }32} 33 else if ( choice == DEPOSIT ) {34 cout << "Enter deposit amount: $";35 cin >> amount;36 cb.deposit( amount );37 cout << "Deposit accepted." << endl;38 }
A Program that Uses the "Checkbook" Class (cont.)
body of the while loop continues
body of the while loop continues
38
39 else { // must be a balance request40 amount = cb.getBalance( );41 cout << "Your balance is: $" << amount << endl;42 }4344 choice = menu( );45 } 4647 return 0;48 }49
A Program that Uses the "Checkbook" Class (cont.)
end of while loop
39
50 int menu( )51 {52 int choice;5354 cout << endl;55 cout << "1 Write a check" << endl;56 cout << "2 Make a deposit" << endl;57 cout << "3 Get the balance" << endl;58 cout << "4 Quit" << endl << endl;59 cout << "Enter a number between 1 and 4: ";60 cin >> choice;61 return choice;62 }
A Program that Uses the "Checkbook" Class (cont.)
Keep In Mind
• The data members of a class cannot be accessed by a main program.
• The object always retains the current values of its data members, even when object code is no longer executing.
• Each function of a class can use the data members of the class as though they have been declared within the function.
40
Maintenance
• Maintenance refers to any work done on a program after it is put into operation
• The world constantly changes• Programs have to be maintained (modified) to
keep up with the changes• When programs are maintained, the data
members sometimes have to change• Private data members make it easier to
maintain a program
41
If Data Members were Accessed Directly…
42
Class
int a;int b;int c;
Main Program
.
.
.Suppose the variables of a class were accessed by 100 places in a program
If Data Members were Accessed Directly… (cont.)
43
Class
int arr[10]
Main Program
.
.
.Then we need to change the way the data is repre-sented (for maintenance)
If Data Members were Accessed Directly… (cont.)
44
Class
int arr[10]
Main Program
.
.
.We need to change 100 lines of code in the main
program!
Data Members ShouldBe Private
45
Class
private:int a;int b;int c;
Main Program
.
.
.Here, the main program calls function “foo” from
100 places.
int foo( int x )
Data Members ShouldBe Private (cont.)
46
Class
private:int a;int b;int c;
Main Program
.
.
.Then foo accesses the private data members.
int foo( int x )
Data Members ShouldBe Private (cont.)
47
Class
private:
int arr[10]
Main Program
.
.
.If the data needs to change, then only the
function “foo” will need to be rewritten.
int foo( int x )
Data Members ShouldBe Private (cont.)
48
Class
private:
int arr[10]
Main Program
.
.
.However, the function call of foo and the return type
will stay the same.
int foo( int x )
Data Members ShouldBe Private (cont.)
49
Class
private:
int arr[10]
Main Program
.
.
.i.e. No changes need to be made in the main
program!
int foo( int x )
Data Members ShouldBe Private (cont.)
50
Class
private:
int arr[10]
Main Program
.
.
.Program maintenance is easier this way…especially
if there is more than one program using the class.
int foo( int x )
Data Members ShouldBe Private (cont.)
51
Class
private:
int arr[10]
Main Program
.
.
.especially if there is more than one program using the class.
int foo( int x )
When Writing a Class
• Your class may be used by hundreds or even thousands of clients (main programmers)
• Write your class for clients, not for computer users
• Do not put code in your class which gives messages to users or asks users for information – let clients handle this the way they want
52
Debugging a Program with Classes
• First technique – make the classes and the main program and test everything all at once– inefficient: takes a long time to track down each
bug
• Second technique – test each class as it is made by writing a main program just to test it (called a test driver or driver)
53
First Technique
54
Class 1
Class 2
Class 3
Class 4
Main
Program
bugs in the classes
Let’s assume it takes 2 hours, on average, to fix each problem.
2nd Technique - Using Drivers
55
Class 1
Class 2
Class 3
Class 4
We’ll try the second technique – write a driver to test each class.
Assume it takes one hour to write a driver.
Fixing a runtime error will be faster – let’s say it takes a half an hour.
Time for first technique: 40:00
Using Drivers (cont.)
56
Class 1
Class 2
Class 3
Class 4 Runtime Errors: 0Time: 14:00Drive
r
Time for first technique: 40:00
Function Definitions in the Class Specification
• The following slides show that function definitions can be placed into the class specification.
• In general, we should avoid doing this because it is a hindrance to program maintenance.
• It is shown here because you will see code written this way during your career.
57
Function Definitions in the Class Specification (cont.)
58
1 // checkbook.h – A class for a checkbook2 class Checkbook3 {4 public:5 void setBalance( float amount ) 6 { balance = amount; }7 bool writeCheck( float amount ); // returns
false if 8 // amount is greater than balance; 9 // otherwise returns true10 void deposit( float amount ) { balance
+= amount; 11 lastDeposit =
amount; }
Function Definitions in the Class Specification (cont.)
59
12 float getBalance( ) { return balance; } 13 float getLastCheck( ) { return lastCheck; } 14 float getLastDeposit( ) { return lastDeposit; }
15 private:16 float balance;17 float lastCheck;18 float lastDeposit;19 };
Function Definitions in the Class Specification (cont.)
60
20 // checkbook.cpp – function definitions for the 21 //Checkbook class22 #include “checkbook.h”2324 bool Checkbook::writeCheck( float amount )25 {26 if ( amount > balance )27 return false;28 balance -= amount;29 lastCheck = amount;30 return true;31 }
Struct vs. Class
• Functions can be placed in a struct, but only when necessary
• The public and private keywords can be left out of a class (rare).
• The public and private keywords can be placed into a struct (rare).
61
Struct vs. Class (cont.)**************
So what is the difference between a struct and a class?
•If public and private are not used in a struct, all data members are public by default.•If public and private are not used in a class, all data members are private by default.
**************KEY SLIDE!!!
62
Conventions
• By convention, we use structs when we want all data members to be public– structs are typically defined and used within the
client’s program, not in a separate file– typically used for records of information
• By convention, we use classes when we want all data members to be private (for maintenance purposes)
63