1 / 33

Announcements

This announcement provides important information and guidelines for Homework 5, which involves updating the Robot class and implementing new member functions. Students are advised to read the document thoroughly and start early. Submission of all project files is required.

patea
Download Presentation

Announcements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Announcements • Homework 5– Robot game will be assigned this week • Due NEXT WEEK Start EARLY! • Common Questions: • Be aware of the flow of the game, read the document for all details • The flow of the game will repeat inside a big while loop until the game ends, we call one run of this loop a “turn” in the document: • Do not use TurnRight in TurnFace member function • Instead Turn the robot to a given direction by updating the private data member directly that you implemented for this HW in recitations • Submit ALL files in your project: main.cpp, robot_modified.cpp, robot_modified.h, minifw_modified.cpp, minifw_modified.h, randgen.h and randgen.cpp • Use the world.rw file in the homework zip to open an example world.

  2. Using, Understanding, Updating, DesigningandImplementing Classes • Chapters 5 (5.4) and partially 6 and 7 • in Chapter 6, up to 6.2.3 • in Chapter 7 • concepts of 7.1 and 7.2 are explained, but different examples are given • Robot class implementation details

  3. RandGen Class • A Tapestry class for random number generation • Add randgen.cpp to your project and have #include "randgen.h" in your program • Four member functions intRandInt(int max = INT_MAX); • returns a random integer in [0..max) intRandInt(int low, int max); • returns a random integer in [low..max] double RandReal(); • returns a random double value in [0..1) double RandReal(double low, double max); • returns a random double value in the range of [low..max] • seenumberguess.cppfor an example program thatuseRandGen

  4. Overloading • In RandGen class, there are two different functions named RandInt • so as RandReal • Using the same name for more than one function is called overloading. • They are differentiated by parameter types • Return types do not differentiate funtions • All member and free functions can be overloaded.

  5. Implementation of Robot Class - 1 • Your next homework will be about updating the Robot class • you will add some new member functionsthat requires to deal with robots.h and robots.cpp files (actually in thehomework, youwilluse an updatedclassforwhichthe file namesarerobots_modified.h androbots_modified.cpp) • and you will use those newly added functions in an application • It is a good idea to have a look at how this class is implemented • It is designed and implemented by ErsinKarabudak • We have made some changes later • Robot class implementation is quite complex • Robot, RobotWindow and RobotWorld are different structures • we will not deal with RobotWindow and RobotWorld, but the implementation file contains robot class implementation and the details of RobotWindow and RobotWorld too. Do not get confused. • Robots are maintained as a circular doubly linked list • it is a data structure that uses pointers (probably will see in CS300) • but do not get thrilled! you will not need those complex structures for the member functions that you will add. • Some details you have to know will be given now and more details will be given in recitations this week

  6. Implementation of Robot Class - 2 constructor enum Direction { east, west, north, south }; enum Color { white, yellow, red, blue, green, purple, pink, orange }; class Robot { public: Robot (int x, int y, Direction dir = east, int things = 0); ~Robot (); void Move (int distance = 1); bool Blocked (); void TurnRight (); bool PickThing (); bool PutThing (); void SetColor (Color color); bool FacingEast (); bool FacingWall (); bool CellEmpty (); bool BagEmpty (); Destructor (not needed in HW5) member functions continued on the next slide

  7. Implementation of Robot Class - 3 private: intxPos; //x coordinate of the location of robot intyPos; //y coordinate of the location of robot Direction direction; //current direction of robot Color color; //current color of robot int bag; //current # of things in the bag of robot bool stalled; //true if the robot is dead bool visible; //true if the robot is visible Robot *next; Robot *prev; static Robot *list; friend structRobotWindow; }; Private Data pointers for the data structure you will not need them RobotWindow may refer Robot’s private data

  8. Implementation of Robot Class - 4 • Previous two slides were in the robots.h (now robots_modified.h). • Now let’s go over the robots.cpp (now robots_modified.cpp) file in VC++ environment • In the next homework, you are going to add 6-8 member functions to the robot class • Some of the member functions will be done in recitations this week • Hints • try to use currently available member functions • e.g. for PickThings, try to use PickThing in a loop rather than writing some thing similar to PickThing • do not hesitate to modify or access private data members when needed • e.g. you will need such an update for TurnFace function • if you change the state of a robot within the current cell, use the following to update the window theRobotWindow->Redraw(this);

  9. Implementation of Robot Class - 5 • Hints for the next homework (cont’d) • you will need to use the function called IsPressed defined in miniFW.h (it is going to be renamed as miniFW_modified.h) • so include this header file to your main program file • this function (IsPressed) is to check whether a key (e.g. an arrow key) is pressed or not - details are in recitations • Some other changes in the Robot World and Robot Class • If a robot hits another robot, both die! • No automatic message is displayed when a robot dies • Now the bag content is written in robots (if not zero) • Use robots_modified.h, robots_modified.cpp, miniFW_modified.h and miniFW_modified.cpp files in HW4 • They will be provided to you in the homework and/or recitation package

  10. Classes: From Use to Implementation (Chapter 6.1) • We’ve used several classes • A class is a collection of objects sharing similar characteristics • A class is a type in C++, like int, bool, double • A class encapsulates state and behavior • string (this is a standard class), needs#include <string> • Objects: "hello", "there are no frogs", … • Methods: substr(…),length(…),find(…),operators such as + and<< • Dateneeds#include "date.h" • Objects: December 7, 1949; November 22, 1963 • Some Methods: MonthName(),DayName(),operator -etc.

  11. State and Behavior • Behavior of a class is what a class does • described in verbs • babies eat, cry • dice are rolled • In OO programming terminology, behavior is defined by public member functions • for Diceclass, member functions are the Diceconstructor, NumRolls(), NumSides()and Roll() • State of a class depends on physical properties • cars have four wheels, different colors • dice have a number of sides • In OO programming, State is defined by private data in the header file • also called member data, instance variables, or data fields • for Dice class, mySides and myRollCount (see dice.h)

  12. Objects • An object is an instance of a class • When created, in memory a set of private data members are allocated and initialized according to the constructor function • In other words, each object has a different state • However, objects share member function implementations • The same function name is used on all objects of the same class • When a member function is called on an object, that object’s private data members are accessed and/or modified

  13. Anatomy of the Dice class • The class Dice • Objects: 6-sided dice, 32-sided dice, one-sided dice • Methods: Roll(),NumSides(),NumRolls() • A Dice object has state and behavior • Each object has its own state, just like each int has its own value • Number of times rolled, number of sides • All objects in a class share method (member function) implementations, but access their own state • How to respond to NumRolls()? Return my own # of rolls

  14. The header file dice.h • Need#include "dice.h"tousethediceclass class Dice { public: Dice(int sides); // constructor int Roll(); // return the random roll intNumSides() const; // how many sides intNumRolls() const; // # times this die rolled private: intmyRollCount; // # times die rolled intmySides; // # sides on die }; • The compiler reads this header file to know what’s in a Dice object • Each Diceobject has its own mySides and myRollCount • generally initialized by the constructor function

  15. The header file is a class declaration • Private data are called instance variables (a.k.a. private data members) • each object has its own private data • Public functions are called methods, member functions, these are called by client programs • All objects of a particular class share the method implementations • The header file is an interface, not an implementation • Description of behavior, analogy to DVD player • Do you know how DVD player operates? • You do not mind, just press the button (interface) and watch! • Square root button on a calculator, how does it calculate? Do you care? • Header file provides information to compiler and to programmers • Compiler determines what methods/member functions can be called for the objects of a class • Programmer reads header file to determine what methods are available, how to use them and other information about the class

  16. What to know? • Client programmer (programmer who uses the classes) needs to know the interface from the header file • public member functions and constructors • parameters, how they behave • does not need to know private data (instance variables) • does not need to know how the member functions are implemented • just need to know where (in which file) it is implemented in order to include the implementation file in the project • As a good programmer who will design and/or update classes, YOU mayneedto know about the class implementations

  17. Objects constructed dodeca dodeca cube cube mySides mySides mySides mySides myRollCount myRollCount myRollCount myRollCount 6 0 0 1 6 12 12 6 Method invoked After for loop From interface to use, the class Dice #include "dice.h" int main() { Dice cube(6); Dice dodeca(12); cout << cube.Roll(); int k; for(k=0; k < 6; k++) { cout << dodeca.Roll(); } return 0; }

  18. From Interface to Implementation • The header file provides compiler and programmer information about how to use a class, but no information about how the class is implemented • Important separation of concepts • use without complete understanding of implementation • Implementation file is a cpp file with no main function • member function and constructor bodies are given • sometimes some other functions are also given

  19. Implementation: the .cpp file • In the implementation file we see all member functions written, similar idea asthe functions we’ve seen so far • Each function has a name, parameter list, and return type • A member function’s name includes its class name return_type class_name :: function_name (parameters) • A constructor is a special member function for initializing an object, constructors have no return type class_name :: class_name (parameters) :: is the scope resolution operator specifies the class of the function • Each method can access private data members of an object (the object on which this member function will operate) • This way, at each invocation, member functioncan access different objects’ private data cube.NumSides() compared to dodeca.NumSides() • dot operator . is used when a member function is called

  20. dice.cpp (Implementation file) – 1/2 Dice::Dice(int sides) // postcondition: all private fields initialized { myRollCount = 0; mySides = sides; } int Dice::NumSides() const // postcondition: return # of sides of die { return mySides; } Constructor

  21. dice.cpp (Implementation file) – 2/2 int Dice::NumRolls() const // postcondition: return # of times die has been rolled { return myRollCount; } int Dice::Roll() // postcondition: number of rolls updated // random 'die' roll returned { RandGen gen; // random number generator myRollCount= myRollCount + 1; // update # of rolls return gen.RandInt(1,mySides); // in range [1..mySides] }

  22. Understanding Class Implementations • Private data members are global such thatthey are accessible byall class member functions • e.g. in the implementation of Rollfunction, mySides and myRollCountare not defined, but used

  23. Understanding Class Implementations • Constructors should assign values to each instance variable • this is what construction is • not a rule, but a general programming style

  24. Understanding Class Implementations • Methods (member functions) can be broadly categorized as accessors or mutators • Accessor methods may access information about an object but do not change the state (private data members) • Dice::NumRolls()andDice::NumSides()are accessor methods since they do not change the private data members • Mutator methods change the state of an object • Dice::Roll(), since it changes an object’s myRollCount

  25. Class Implementation Heuristics • All data should be private • Provide accessor and mutatormember functions as needed • Make accessor functions const • by putting constafter all parameters • in both class definition (header file) and class implementation • A constfunction cannot modify the state of an object • precaution against poor implementations • compilers do not allow to update private data in constfunctions int Dice::NumSides() const // postcondition: return # of sides of die { return mySides; }

  26. The class Date • The class Date is accessible to client programmers #include "date.h" • to get access to the class • The compiler needs this information. • It may also contain documentation for the programmer • Link the implementation in date.cpp • Addthis cpp toyourproject • The class Date models a calendar date: • Month, day, and year make up the state of a Date object • Dates can be printed, compared to each other, day-of-week determined, # days in month determined, many other behaviors • Behaviors are called methods or member functions

  27. Constructing Date objects – see usedate.cpp Date today; Date republic(10,29,1923); Date million(1000000); Date y2k(1,1,2000); cout << "today: " << today << endl; cout << "Republic of Turkey has been founded on: " << republic << endl; cout << "millionth day: " << million << endl; OUTPUT today: April 4 2016 Republic of Turkey has been founded on: October 29 1923 millionth day: November 28 2738

  28. Constructing/defining an object • Date objects (as all other objects) are constructed when they’re first defined • Three ways to construct a Date • default constructor, no params, initialized to today’s date • single long int parameter, number of days from January 1, 1 • three params: month, day, year (in this order). • Constructors for Date objects look like function calls • constructor is a special member function • Different parameter lists mean different constructors • Once constructed, there are many ways to manipulate a Date • Increment it using ++, subtract an integer from it using -, print it using cout, … • MonthName(), DayName(), DaysIn(), … • See date.h for more info on date constructors and member functions

  29. Date Member Functions Date MidtermExam(18,4,2016); • Construct a Date object given month, day, year MidtermExam.DayName() • Returns the name of the day (“Monday” or “Tuesday”, or ...) • in this particular case, returns “Monday” since December 1, 2014is a Monday MidtermExam.DaysIn() • Returns the number of days in the particular month • in our case return 31, since December 2014 has 31 days in it • Add, subtract, increment, decrement days from a date Date GradesDue = MidtermExam + 9; • GradesDue is April27, 2016 • Let’s see usedate.cpp in full and datedemo.cpp now

  30. Example: Father’s day (not in book) • Father’s day is the third Sunday of June • write a function that returns the date for the father’s day of a given year which is the parameter of the function • In main, input two years and display father’s days between those years Date fathersday(int year) // post: returns fathers day of year { Date d(6,1,year); // June 1 while (d.DayName() != "Sunday") { d += 1; } //d is now the first Sunday, 3rd is 14 days later return d + 14; } • See fathersday.cpp for full program

  31. What if there were no date class? • It would be very cumbersome to deal with dates without a date class • imagine banking applications where each transaction has associated date fields • Classes simplify programming • they are designed and tested. • then they can be used by programmers • You are lucky if you can find ready-to-use classes for your needs • otherwise ???

  32. Updating a Class (not in book) • Suppose you want to add more functionality to the date class • need to change the header file (date.h) • need to add implementation of new function(s) to date.cpp • Example: a new member function to calculate and return the remaining number of days in the object’s month • any ideas? do you think it is too difficult? • have a look at the existing member functions and see if they are useful for you

  33. Updating a Class (not in book) • We can make use of DaysIn member function • Prototype in Date class (add to the header file) intRemainingDays() const; • Implementation intDate::RemainingDays () const { return DaysIn()-myDay; } • In a member function implementationprivate data and other member functions referred without the dot operator. • Theyoperate on the object for which the member function is called

More Related