1 / 17

Classes: Using Classes Together Wrap-Up

Classes: Using Classes Together Wrap-Up. CMPSC 122 Penn State University Prepared by Doug Hogan. Preview of Today…. Objects as members of classes Destroying objects Defining operators. Using Classes Together. Classes can be used as private data of other classes.

dugan
Download Presentation

Classes: Using Classes Together Wrap-Up

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. Classes:Using Classes TogetherWrap-Up CMPSC 122 Penn State University Prepared by Doug Hogan

  2. Preview of Today… • Objects as members of classes • Destroying objects • Defining operators

  3. Using Classes Together • Classes can be used as private data of other classes. • Example: create a simple Time class: • class Time{ public: Time();// POST: default Time object constructed s.t. // hour == 0, minute == 0void setTime(int newHour, int newMin); // PRE: 0 <= newHour <= 23, 0 <= newMin <= 59 // POST: hour == newHour, min == newMinint getHour() const;// POST: FCTVAL == hour int getMin() const; // POST: FCTVAL == minuteprivate: int hour; // hour, 0-23 format int min; // minute, 0-59 format};

  4. Using Classes Together • Use the Time class in our tvShow class • class tvShow{ public: …private: string name; // title of this show int channel; // number of channel // airing this showTime startTime; // time this show starts};

  5. Exercise: Using Classes Together • Implement the tvShow constructor with this new setup. tvShow::tvShow() // POST: default tvShow is constructed s.t. // name = "new show," channel = 2, // startTime = 0:00 (12 a.m.) { name = "new show"; channel = 2; // startTime -- implicit // default constructor call }

  6. Exercise: Using Classes Together • Implement a function to print the start time in the format “8:30 a.m.” with this new setup. • Where is the best place to do this? • Time class knows stuff about times – add it there • Note: tvShow is now a client of Time • We say there's a "has a" relationship between these classes; this is called composition of classes (more in 221 on that) • Default constructor call was implicit • Define Time operations in Time class; use in tvShow

  7. Destructors • Another type of member function • Called automatically when objects go out of scope • Properties: • Name: ~ClassName(); • e.g. ~bankAccount(); • Never have parameters • Useful when classes have pointers as data members or otherwise allocate memory that needs to be deallocated. • Otherwise, would just overcomplicate, so omit

  8. Destructor Example • Suppose we're implementing a simple container class ScoreList that maintains a list of scores and has these private data: • int scores[];int logicalSize;int physicalSize; • We want to be able to resize the array if needed, so we'll make it dynamic (See Lecture 5). • Our constructor might do the following: • physicalSize = 100;logicalSize = 0;scores = new int[physicalSize];

  9. Destructor Example, ctd. • Since we have dynamic memory, we need to "clean up" at the end. • So we need a destructor to deallocate the dynamic array: • ScoreList::~ScoreList(){ delete [] scores;}

  10. A Problem to Consider: Fractions • Let's say we want to make a class to model fractions. • What member data should we have? • int numer; // fraction's numerator • int denom; // fraction's denominator • We'll need some operations. Let's assume we have some basics: • A default constructor and an initializer constructor for both data • Setters and getters for all fields

  11. A Problem to Consider: Fractions • What other operations might be natural? • Add one to a fraction • Add two fractions • Output a fraction • Exercise: Implement this member function… • void AddOne()// POST: the decimal value of this fraction// has been increased by one • { numer += denom;}

  12. Operator Overloading • Let's say we had two fraction objects frac1 and frac2… • If they were primitives, it might be nice to… • Add one to a fraction by saying frac1++ • Add two fractions by saying frac1 + frac2 • It turns out we can! • But we have to define what the operators ++, +, and << mean when their operands are fractions • Operators take on different meanings for different types of operands. Practice called operator overloading.

  13. Overloading a Unary Operator • A unary operator has one operand. • To overload a unary operator for a class… • Make a member function operator[symbol], e.g. operator++ • Example: • Interface: void operator++();// POST: the decimal value of this fraction// has been increased by one • Implementation: void FracType::operator++()// POST: the decimal value of this fraction// has been increased by one{ numer += denom;}

  14. Overloading a Binary Operator • A binary operator has two operands. • Overloading a binary operator is similar to a unary operator, but we need to take a second instance of the class as a parameter • Addition Example: • Interface: Fraction operator+(Fraction frac2);// PRE: this and frac2 are in simplest terms// POST: FCTVAL == sum of this and frac2 (fraction// addition) in simplest terms

  15. Problem: Implement + Operator • Fraction Fraction::operator+(Fraction frac2)// PRE: this and frac2 are in simplest terms// POST: FCTVAL == sum of this and frac2 (fraction// addition) in simplest terms • { Fraction result; // FCTVAL int resultNumer; // numerator of result int resultDenom; // denominator of result • // Recall that a/b + c/d = (ad + bc)/bd, so... • resultNumer = numer*frac2.denom + denom*frac2.numer; resultDenom = denom*frac2.denom; • result.setNumer(resultNumer); result.setDenom(resultDenom); return result; }

  16. Closing Thoughts • What does private mean? • Only the class can access the data member. • We could have used frac2.getDenom(), but since we're in the Fraction class, frac2.denom is okay. • Not all languages allow operator overloading! • So, this isn't the most important of topics. • I won't ever test you on operator overloading syntax (look that up when you need it), but could ask you about the concept.

  17. Summary • Classes can be used within classes • Very practical and important OO concept • Destructors de-allocate memory created by objects • Operator overloading lets you redefine operators for classes you make • I won't test you on the syntax of destructors or operator overloading – look that up when you need it – but I could test you on the concepts

More Related