Classes: Classes: Implementation and Implementation and
TestingTesting
Edited for CMPSC 122Edited for CMPSC 122Penn State UniversityPenn State University
Prepared by Doug HoganPrepared by Doug Hogan
11
Preview of Today…Preview of Today…ImplementationImplementation
Tips for implementing each kind of functionTips for implementing each kind of functionMore ExamplesMore Examples
Client end -- Test driversClient end -- Test drivers
22
ReviewReviewQuestions on Questions on the blue worksheetthe blue worksheet??
33
Implementing Implementing FunctionsFunctions
RememberRememberImplementation outside the class interfaceImplementation outside the class interfaceName of the class and scope resolution operator (Name of the class and scope resolution operator (::::) ) before the FUNCTION NAMEbefore the FUNCTION NAME
44
Implementing Implementing ConstructorsConstructors
Do whatever is necessary to set up the classDo whatever is necessary to set up the class
Initialize each private memberInitialize each private memberDefault constructors: Default constructors:
default valuesdefault valuesInitializer constructors:Initializer constructors:
some from input parameterssome from input parametersvalidate? validate?
set others to default valuesset others to default values
55
ExerciseExerciseImplement the default constructor for Implement the default constructor for tvShowtvShow..
tvShow::tvShow()tvShow::tvShow(){{ name = “New show”;name = “New show”; channel = 2;channel = 2; startHour = 0;startHour = 0; startMin = 0;startMin = 0;}}
66
Implementing initializer Implementing initializer constructorsconstructors
Most specify SOME, not ALL, initial valuesMost specify SOME, not ALL, initial values
Set the others as in the default constructorSet the others as in the default constructor
77
Initializer constructor Initializer constructor exampleexample
tvShow::tvShow(string initName, int initChannel)tvShow::tvShow(string initName, int initChannel){{ name = initName; name = initName; // initialized from// initialized from channel = initChannel; channel = initChannel; // parameters// parameters
// we still need to handle two data members!// we still need to handle two data members! startHour = 0; startHour = 0; // initialized to// initialized to startMin = 0; startMin = 0; // defaults// defaults}}
88
tvShow object constructed with this method
name channel startHour startMin
d
value of initName
from init-Channel 0 0
Implementing Implementing modifiersmodifiers
Ultimately: must have assignment statements (or Ultimately: must have assignment statements (or function calls) that change private datafunction calls) that change private data
99
Modifier ExampleModifier Examplevoid tvShow::reschedule(int hoursLater, void tvShow::reschedule(int hoursLater,
int minutesLater) int minutesLater)// PRE: hoursLater >= 0, 0 <= minutesLater <= 59// PRE: hoursLater >= 0, 0 <= minutesLater <= 59// POST: this tvShow now starts hoursLater hours and// POST: this tvShow now starts hoursLater hours and// minutesLater minutes after it did before// minutesLater minutes after it did before{{ startHour = ((startMin + minutesLater)/60 startHour = ((startMin + minutesLater)/60 + startHour + hoursLater)%24;+ startHour + hoursLater)%24;
// add on hour from minutes rolling over // add on hour from minutes rolling over // add on hours, correct for day rolling over // add on hours, correct for day rolling over
startMin = (startMin + minutesLater)%60; startMin = (startMin + minutesLater)%60; // add on time, correct for new hour// add on time, correct for new hour
}}
1010
Implementing Implementing AccessorsAccessors
““Get” accessorsGet” accessorsreturn a private variablereturn a private variableex:ex:int tvShow::getChannel() constint tvShow::getChannel() const{{ return channel; return channel;}}
Don’t forget the Don’t forget the constconst if it’s in the prototype!if it’s in the prototype!
1111
Accessors That Print vs. Accessors That Print vs. Accessors That ReturnAccessors That Return
int tvShow::getChannel() constint tvShow::getChannel() const// POST: Method // POST: Method returnsreturns this show’s channel this show’s channel {{ return channel; return channel;}}
void tvShow::printChannel() constvoid tvShow::printChannel() const// POST: Method // POST: Method displaysdisplays this show’s channel this show’s channel {{ cout << "Channel: " << channel; cout << "Channel: " << channel;}}
Always provide the first type. The second type can be Always provide the first type. The second type can be useful, but from a user interface design perspective, useful, but from a user interface design perspective, really ought to be avoided. A general principle is that really ought to be avoided. A general principle is that you should separate logic from user interface at all you should separate logic from user interface at all times. times.
1212
An Accessor ExerciseAn Accessor ExerciseWrite an accessor that prints the time of a Write an accessor that prints the time of a tvShow tvShow in the in the format “8:30 a.m.”format “8:30 a.m.”
1313
An Accessor ExerciseAn Accessor Exercisevoid tvShow::printTimeAMPM() constvoid tvShow::printTimeAMPM() const// POST: a string is displayed with this// POST: a string is displayed with this// show's start time in "h:mm a.m." form// show's start time in "h:mm a.m." form{{ int hr; // hour in format 1..12int hr; // hour in format 1..12
hr = startHour%12; // get hour in 0..12 rangehr = startHour%12; // get hour in 0..12 rangeif(hr == 0) // correct for hour 0 == 12if(hr == 0) // correct for hour 0 == 12
hr = 12; hr = 12;
if(min <= 9) // need leading zeroif(min <= 9) // need leading zero cout << hr << ":0" << min; cout << hr << ":0" << min; else // no leading zeroelse // no leading zero cout << hr << ":" << min; cout << hr << ":" << min;
if(startHour < 12) // check for a.m.if(startHour < 12) // check for a.m. cout << " a.m.";cout << " a.m.";else // otherwise it's p.m.else // otherwise it's p.m. cout << " p.m.";cout << " p.m.";
}} 1414Question: Can any of the if statements be optimized?
Test DriversTest DriversMain program that checks whether the class is working Main program that checks whether the class is working properlyproperly
Create a few objectsCreate a few objectsCall each of the member functionsCall each of the member functionsCheck the resultsCheck the results
Good practice: test drive classes before writing programs Good practice: test drive classes before writing programs with themwith them
Find the errors WITHIN THE CLASS vs. outside the classFind the errors WITHIN THE CLASS vs. outside the class
1515
Example Test DriverExample Test Driverint main()int main(){{ bankAccount acct1; bankAccount acct1; // def. constructor// def. constructor bankAccount acct2("Homer", 100); bankAccount acct2("Homer", 100); // one init constr// one init constr bankAccount acct3("Lisa");bankAccount acct3("Lisa"); // another init con// another init con
acct1.resetAcct("Marge", 75);acct1.resetAcct("Marge", 75); // test resetAcct// test resetAcct cout << acct1.getName();cout << acct1.getName(); // test getName// test getName
// did resetAcct work?// did resetAcct work? cout << acct1.getBalance();cout << acct1.getBalance(); // test getBalance // test getBalance
// did resetAcct work?// did resetAcct work? acct1.deposit(50);acct1.deposit(50); // deposit// deposit cout << acct1.getBalance();cout << acct1.getBalance(); // did deposit work?// did deposit work? acct1.withdraw(100);acct1.withdraw(100); // withdraw// withdraw cout << acct1.getBalance();cout << acct1.getBalance(); // did withdraw work?// did withdraw work?
// additional calls, use accessors to see that other// additional calls, use accessors to see that other // constructors worked// constructors worked}}
1616
Note: Comments in this test driver are for you. I'll never require test driver comments.
SummarySummaryImplementationImplementation
Scope resolution operator and class nameScope resolution operator and class nameConstructors – initialize each private memberConstructors – initialize each private memberModifiers – change private membersModifiers – change private membersAccessors – remember const, printing vs. returningAccessors – remember const, printing vs. returning
Test drive classes before using themTest drive classes before using them
Lab time now: Your turn to make your own Lab time now: Your turn to make your own class! class!
1717