1 fall 2002 acs 168 problem solving using the computer weeks 9 and 10 structures and classes class...
TRANSCRIPT
1
Fall 2002Fall 2002
ACS 168ACS 168Problem Solving Using the ComputerProblem Solving Using the Computer
ACS 168ACS 168Problem Solving Using the ComputerProblem Solving Using the Computer
Weeks 9 and 10
Structures and Classes
Class Diagrams
Weeks 9 and 10
Structures and Classes
Class Diagrams
2
Chapter 6Defining Classes and Abstract Data
Types
Structures Structures for Diverse Data Types Structures as Function Arguments Initializing Structures
Classes Defining Classes and Member Functions Public and Private Members Summary of Properties of Classes Constructors for Initialization
Abstract Data Types Classes to Produce ADTs
3
Some terms
Object a special variable with its own special functions
as well as data example: cin is an object of the istream class
Class a data type whose variables are objects
Abstract data type a programmer defined data type, such as a
class, that meets certain standards.
4
6.1 Structures A language feature for grouping of related data
Provides a way to represent a collection of related data using a single unit.
A record with fields A structure definition defines a type
struct CDAccount structure tag {
double balance; Member names double interest_rate;
int term; // months until maturity }; DON’T FORGET THE SEMICOLON
5
Declaring structure variables: CDAccount Scott123; // declaration of CDAccount
//structure variable Scott123
Declaration with initialization: CDAccount Scott456 = {2550.00, .07, 24};
Assignment statements for member variables: Scott123.balance = 3000.00; Scott123.interest_rate = .10; Scott123.term = 36; Scott456 = Scott123; // assigns Scott456 values of Scott123 Scott123.balance = Scott456.balance; // assigns balance value
6
Specify member variables with the dot operator
structure_name.member_variable_name
Scott123.balance = 30000.00 Use member variables like any other variables Different structures may have same member variable
names example
CDAccount //structure for account with balance, interest_rate, and term member variables
SavingAccount // structure for savings account with balance, interest_rate, and term member variables
7
Example of program using a StudentRecord structure:
#include <iostream> using namespace std;
struct StudentRecord{ int student_number; char grade;};
int main( ){ StudentRecord your_record; your_record.student_number = 2001; your_record.grade = ‘A’; cout << “The grade for student “
<< your_record.student_number << “ is “ << your_record.grade << endl;
}
8
Try this
Given the structure and structure variable declaration:
struct CDAccount{ double balance; double interest_rate; int term; char initial1; char initial2;}
CDAccount account;
What is the type of each of the following? Which ones are not correct?
a. account.balanceb. account.interest_ratec. CDAccount.termd. saving_account.initial1e. account.intital2f. account
9
Practice 11. Define a structure type named PartRecord with the following
fields: an integer partNumber a double price an integer numOnHand an integer numOrdered
2. Declare two variables, partA and PartB of type PartRecord
3. Declare a PartRecord named partC, initializing it to be part number 151, with price 9.30, 10 on hand, and 0 ordered.
Lect. Notes,
10
4. Write a function that gets information about a part from the user then returns a PartRecord. The function should have no parameters.
5. Write a function that updates a PartRecord because of the arrival of a shipment of parts. The function should accept the PartRecord and an integer number of parts and change both the number on hand and the number on order to reflect that the indicated number of parts that were ordered are not on hand.
Structures as Function Arguments
A function can have call-by-value parameters of structure type and/or call-by-reference parameters of structure type and/or return type that is a structure type
Example of returning structure:
CDAccount shrink_wrap(double the_balance, double the_rate, int the_term){ CDAccount temp; temp.balance = the_balance; temp.interest_rate = the_rate; temp.term = the_term; return temp;} 11
12
More on Initializing Structures
A structure may be initialized at the time it is declared. struct Date
{ int month; int day;
int year; };
Date due_date = { 12, 31, 2001};
Variables in the structure are initialized in order It is an error to have more initializers than variables.
If there are fewer initializers than variables, the initializers provided are used to initialize the data members. The remainder are initialized to 0 for primitive types.
13
Use of Hierarchical Structures
Structures may be nested.
Example: A PersonInfo struct might include a date structure for birthday
struct Date{ int month; int day;
int year; };
struct PersonInfo{ double height; // inches int weight; // pounds Date birthday; // Date structure};
14
Use Hierarchical Structures, cont.
Declare a variable of PersonInfo type as usual: PersonInfo person1;
person1.birthday // This is a Date structure, with members accessible
// as in any other structure variable.
If the structure variable person1 has been set, the year a person was born can be output as follows:
cout << person1.birthday.year;
structure person1 structure birthday structure variable member member
6.2 Classes Defining Classes and Member Functions
A class is also a user defined data type Class variables are called objects An object is a variable that
Has member variables (data members) and can hold multiple values (like a structure)
Also has member functions (methods)
A class definition specifies the data members (much like a structure definition) and the member functions
15variablesvariables functionsfunctions classclass
16
A class is a blueprint from which objects
are created
17
Defining a Class
class DayOfYear{public:
void output( ); member function prototype int month; data members int day;
};
The scope of a class starts at the name of the class in the class definition and runs to the closing curly brace and semicolon.
Member functions are declared inside of the class definition, but are usually defined outside of it (unless very short)
// Display 6.3 Class with a Member Function (1 of 2)// Program to demonstrate a very simple example of a class.
#include <iostream>using namespace std;
class DayOfYear class name { public: void output( ); member function prototype int month; int day;};
int main( ){ DayOfYear today, birthday; // declaration of two objects of DayOfYear class
cout << "Enter today's date:\n"; cout << "Enter month as a number: "; cin >> today.month; cout << "Enter the day of the month: "; cin >> today.day; cout << "Enter your birthday:\n"; cout << "Enter month as a number: "; cin >> birthday.month; cout << "Enter the day of the month: "; cin >> birthday.day;
18
// Display 6.3 Class with a Member Function (1 of 2)
cout << "Today's date is "; today. output( ); calls to the member function output cout << "Your birthday is "; birthday.output( ); the calling object if (today.month == birthday.month && today.day == birthday.day) cout << "Happy Birthday!\n"; else cout << "Happy Unbirthday!\n";
return 0; class name} scope resolution operator
//Uses iostream:
void DayOfYear :: output( ) member function definition
{
cout << "month = " << month
<< ", day = " << day << endl;
}
19
Note :do not need dot operator for month and day
20
Defining Member Functions, cont.
One line member functions may be defined within the class definition.
Longer member functions should be defined outside the class definition.
Use the scope resolution operator :: to define a member function outside of the class definition
similar to dot operator that is used with object members class name called the type qualifier
return_type Class_name :: Function_name(Parameter_list)
void DayOfYear :: output( ) //member function definition
{ cout << "month = " << month << ", day = "
<< day << endl;}
21
Defining Member Functions, cont.
Can use names of any data members and member functions in that class without the dot operator. Considered to be within the scope of the class.
void DayOfYear :: output( ){ cout << “month = “ << month << “ , day = “ << day << endl;}
void DayOfYear :: output( ){ cout << “month = “ << month << “ , day = “ << day << endl;}
22
Using Objects in a Program
Objects of a class type are declared much the same as structure variables DayOfYear birthday, Thanksgiving;
Class member variables are specified using the dot operator
member functions are called using the dot operator
birthday.month birthday.output();
object dot variable object dot member
name operator name name operator function
23
Encapsulation and Information Hiding
Encapsulation Combining several items such as variables, or variables and
functions, into a single package, such as an object of a class.
Information hiding – the black box concept Each object knows how to perform its own functions, how
to interact (interface) with other objects, but does not need to know how the other objects work (are implemented)
The goal is to allow the user to know how to use the functions, but does not need to know how the function is implemented
24
Public vs. Private Class Members
use in class definition to label the member variables and member functions
public members public: can be accessed from any function, including main( )
private members private: these members can only be accessed inside the class’ own
member functions, not by outside functions. private is the default best to make all member variables private
Use terms public and private in any order, any number of times in class definition
Display 6.4 Class with Private Members (1 of 3)//Program to demonstrate the class DayOfYear.#include <iostream>using namespace std;
class DayOfYear{public: void input( ); void output( );
//mutator function void set(int new_month, int new_day); //Precondition: new_month and
new_day form a possible date. //Postcondition: The date is reset according to the arguments.
//accessor functions int get_month( ); {
return month; } int get_day( );{ return day;
} private: int month; int day;};
25
A better class definition:A better class definition:
Display 6.4 Class with Private Members (3 of 3)//Uses iostream:void DayOfYear::input( ){ cout << "Enter the month as a number: "; cin >> month; cout << "Enter the day of the month: "; cin >> day;}
void DayOfYear::output( ){ cout << "month = " << month << ", day = " << day << endl;}
void DayOfYear::set(int new_month, int new_day){ month = new_month; day = new_day;}
26
Display 6.4 Class with Private Members (2 of 3)
int main( ){ DayOfYear today, bach_birthday; cout << "Enter today's date:\n"; today.input( ); cout << "Today's date is "; today.output( );
bach_birthday.set(3, 21); cout << "J. S. Bach's birthday is "; bach_birthday.output( );
if ( today.get_month( ) == bach_birthday.get_month( ) && today.get_day( ) == bach_birthday.get_day( ) ) cout << "Happy Birthday Johann Sebastian!\n"; else cout << "Happy Unbirthday Johann Sebastian!\n"; return 0;}
27
28
Why Public and Private Members?
With an ideal class definition, the class author should be able to change the details of the class implementation without necessitating changes in any program using the class .
Use accessor (getter) functions to access the data members that are private and cannot be accessed directly.
Use mutator (setter) functions to change values in private member variables
29
Members defined after “public:” up to the next “private:” or other access specifier keyword are accessible by all functions.
Members defined after “private:” up to the next public: or other access keyword are accessible only by all functions defined in the class.
Public and Private Members
Display 6.5 The Bank Account Class (1 of 3)//Program to demonstrate the class BankAccount.#include <iostream>using namespace std;//Class for a bank account:class BankAccount{public: void set(int dollars, int cents, double rate); //Postcondition: The account balance has been set to $dollars.cents; //The interest rate has been set to rate percent.
void set(int dollars, double rate); //Postcondition: The account balance has been set to $dollars.00. //The interest rate has been set to rate percent.
void update( ); //Postcondition: One year of simple interest has been //added to the account balance.
double get_balance( ); //Returns the current account balance.
double get_rate( ); //Returns the current account interest rate as a percent.
void output(ostream& outs); //Precondition: If outs is a file output stream, then //outs has already been connected to a file. //Postcondition: Account balance and interest rate have been written // to the stream outs.
30
Display 6.5 The Bank Account Class (2 of 3)
// class BankAccount
private: double balance; double interest_rate; double fraction(double percent); //Converts a percent to a fraction. For example, fraction(50.3) returns 0.503.};
int main( ){ BankAccount account1, account2; cout << "Start of Test:\n";
account1.set(123, 99, 3.0); cout << "account1 initial statement:\n"; account1.output(cout);
account1.set(100, 5.0); cout << "account1 with new setup:\n"; account1.output(cout);
account1.update( ); cout << "account1 after update:\n"; account1.output(cout);
account2 = account1; cout << "account2:\n"; account2.output(cout); return 0;}
31
Display 6.5 The Bank Account Class (3 of 3)void BankAccount::set(int dollars, int cents, double rate){ balance = dollars + 0.01*cents; interest_rate = rate;}void BankAccount::set(int dollars, double rate){ balance = dollars; interest_rate = rate;}void BankAccount::update( ){ balance = balance + fraction(interest_rate)*balance;}double BankAccount::fraction(double percent){ return (percent/100.0);}double BankAccount::get_balance( ){ return balance;}double BankAccount::get_rate( ){ return interest_rate;}void BankAccount::output(ostream& outs){ outs.setf(ios::fixed); outs.setf(ios::showpoint); outs.precision(2); outs << "Account balance $" << balance << endl; outs << "Interest rate " << interest_rate << "%" << endl;}
32
33
Programming Tips Make Data Members private
make all member variables private. This means these variables can only be accessed or changed using member functions.
Define Accessor Functions. consider providing a complete set of accessors to data in
useful formats. This will make comparing objects for equality easier.
Use the Assignment Operator with Objects: The assignment operator = applies to struct and class objects. You can use it to “copy” the same values from one object to another.
Summary of Properties of Classes
1. Classes have both member variables and member functions.
2. A member (either variable or function) may be public or private.
3. Normally, all variable members of a class are private.
4. A private member of a class cannot be used except in the definition
of a member function of the same class.
5. The name of a member function for a class may be overloaded just
as the name of an ordinary function.
6. A class may use another class as the type for a member variable.
7. A function may have formal parameters whose types are classes.
8. A function may return an object.
34
35
Constructors for Initialization
constructor is what “builds” the object. You can write your own constructors or C++
will provide a default constructor for you. A class constructor has the same name as the
class. A constructor does not return a value, not
even void. (This is the only type of function that does not have a return value.)
C++ provides a special kind of member function known as a constructor for automatic initialization of class objects at definition.
36
Constructors for Initialization
Each constructor should provide a value for every member variable.
If the programmer does not write an explicit constructor, a default constructor is automatically provided. However, if any constructor is coded, this automatic default constructor is not provided.
Constructors can be written to allow input of values for some or all variables.
Class constructors may be overloaded as needed. A default constructor should ALWAYS be included in every
class definition. If you write any constructor at all, you should also write a default constructor
37
Constructors for Initialization in a Program
class BankAccount{public:// Constructors BankAccount(); // default constructor BankAccount( int dollars, int cents, double rate); . . .Private: double balance; double interest_rate;};BankAccount::BankAccount(int dollars, int cents, double rate){ balance = dollars + .01 * cents; interest_rate = rate;}
Calling a Constructor
A constructor is called automatically when an object is declared. If you are not using the default constructor, you must give the arguments for the constructor when you declare the object.
Syntax: ClassName ObjectName(Arguments_for_Constructor);
Example: BankAccount account1(100, 2.3);
A constructor can be called explicitly (later in program after object declaration):
Syntax: ObjectName = ConstructorName(Arguments_for_Constructor);
Example: account1 = BankAccount(200, 3.5);
A constructor must have the same name as the class of which it is a member. Hence Class_Name and Constructor_Name are the same identifier.
38
Pitfall: Constructors with no arguments
Call to constructor that requires two parameters.
BankAccount object_name(100, 2.3);
Call to constructor that takes no parameters:
BankAccount object_name;
NOT a call to no-parameter constructor. BankAccount objectname();
Compiler would see this as a function that returns an object of BankAccount type.
39
6.3 Abstract Data Types
A data type is called an Abstract Data Type (ADT) if the programmers who use the type do not have access to the details of how the values and operations are implemented.
Programmer defined types are not automatically ADTs.
ADTs should allow the programmer to easily use them in their code.
40
Classes to Produce ADTs: How to make an ADT
Make member variables private Make a public member function of the class for each of the
basic operations that the programmer needs Fully specify how to use each such function (use clear
comments and pre and post conditions).
Make helping functions private member functions
The interface should tell all the programmer need to know to
use the ADT. include the public member functions along with commentary telling
how to use the member functions.
User of the class does not need to know about implementation of member functions
41
Information Hiding
Write member functions so that they can be used with no
knowledge of how they were written: as if they were black boxes.
All the programmer needs to know about a function is its
prototype and accompanying comment that explains how to use
the function.
Make use of private member variables and private member
functions
42
43
The Class Diagram
BankAccount
-balance: double-interest_rate: double
+BankAccount (dollars, cents, rate)+BankAccount(dollars, rate)+BankAccount( )+update( ): void+get_balance( ): double+get_rate( ): double+output(outs): void-fraction(percent): double
Class name
member variables
member functions (with parameters)
function return type
+ public members- private members
44
Class Problem 6.
Define a class named Part with the same data members as ourPartRecord structure and the following member functions:
Input, which gets information from the user and fills in each data member–Output, which writes out the information about a part–Receive, which takes a number of parts received and updates
the number on hand and the number ordered accordingly–Sell, which takes a number of parts sold and updates the
number on hand–Order, which takes a number of parts ordered and updates the number on order–GetNumOnHand, which returns the number of parts on hand–GetNumOnOrder, which returns the number of parts on
order