Classes: From Use to ImplementationAnatomy of the Dice classThe header file dice.hAnatomy of a header fileThe header file is a class declarationFrom interface to use, the class DiceHeader file as InterfaceWilliam H. (Bill) Gates, (b. 1955)From Interface to ImplementationImplementation, the .cpp fileMore on method implementationUnderstanding Class ImplementationsClass Implementation HeuristicsBuilding Programs and ClassesDesign HeuristicsDesign Heuristics continuedReference parametersQuadratic Equation ExampleWho supplies memory, where’s copy?ExamplesA Computer Science Tapestry6.1Classes: From Use to ImplementationWe’ve used several classes, a class is a collection of objects sharing similar characteristicsA class is a type in C++, like int, bool, doubleA class encapsulates state and behaviorA class is an object factorystring (this is a standard class), need #include <string>Objects: "hello", "there are no frogs", …Methods: substr(…), length(…), find(…), <<Date need #include "date.h"Objects: December 7, 1949, November 22, 1963Methods: MonthName(), DaysIn(), operator -A Computer Science Tapestry6.2Anatomy of the Dice classThe class Dice, need #include "dice.h"Objects: six-sided dice, 32-sided dice, one-sided diceMethods: Roll(), NumSides(), NumRolls()A Dice object has state and behaviorEach object has its own state, just like each int has its own value•Number of times rolled, number of sidesAll objects in a class share method implementations, but access their own state•How to respond to NumRolls()? Return my own # rollsA Computer Science Tapestry6.3The header file dice.hclass Dice{ public: Dice(int sides); // constructor int Roll(); // return the random roll int NumSides() const; // how many sides int NumRolls() const; // # times this die rolled private: int myRollCount; // # times die rolled int mySides; // # sides on die};The compiler reads this header file to know what’s in a Dice objectEach Dice object has its own mySides and myRollCountA Computer Science Tapestry6.4Anatomy of a header fileA Computer Science Tapestry6.5The header file is a class declarationWhat the class looks like, but now how it does anythingPrivate data are called instance variablesSometimes called data members, each object has its ownPublic functions are called methods, member functions, these are called by client programsThe header file is an interface, not an implementationDescription of behavior, analogy to stereo systemSquare root button, how does it calculate? Do you care?Information hiding and encapsulation, two key ideas in designing programs, object-oriented or otherwiseA Computer Science Tapestry6.6From interface to use, the class Dice#include “dice.h”int main(){ Dice cube(6); Dice dodeca(12); int x = cube.Roll(); int k; for(k=0; k < 6; k++) { x = dodeca.Roll(); } return 0;}Objects constructedcube.myRollCount == 0cube.mySides == 6dodeca.myRollCount == 0dodeca.mySides == 12Method invokedAfter for loopcube.myRollCount == 1cube.mySides == 6dodeca.myRollCount == 6dodeca.mySides == 12A Computer Science Tapestry6.7Header file as InterfaceProvides information to compiler and to programmersCompiler determines how big an object (e.g., Dice cube(6)) is in memoryCompiler determines what methods/member functions can be called for a class/objectProgrammer reads header file (in theory) to determine what methods are available, how to use them, other information about the classWhat about CD, DVD, stereo components?You can use these without knowing how they really workWell-designed and standard interface makes it possible to connect different componentsOO software strives to emulate this conceptA Computer Science Tapestry6.8William H. (Bill) Gates, (b. 1955)CEO of Microsoft, richest person in the world (1999)First developed a BASIC compiler while at HarvardDropped out (asked to leave?) went on to develop Microsoft“You’ve got to be willing to read other people’s code, then write your own, then have other people review your code”Generous to Computer Science and philanthropic in generalVisionary, perhaps cutthroatA Computer Science Tapestry6.9From Interface to ImplementationThe header file provides compiler and programmer with how to use a class, but no information about how the class is implementedImportant separation of concerns, use without complete understanding of implementationImplementation can change and client programs won’t (hopefully) need to be rewritten•If private section changes, client programs will need to recompile•If private section doesn’t change, but implementation does, then client programs relinked, but not recompiledThe implementation of foo.h is typically in foo.cpp, this is a convention, not a rule, but it’s well established (foo.cc used too)A Computer Science Tapestry6.10Implementation, the .cpp fileIn the implementation file we see all member functions written, same idea as functions we’ve seen so farEach function has name, parameter list, and return typeA member function’s name includes its classA constructor is a special member function for initializing an object, constructors have no return typeDice::Dice(int sides)// postcondition: all private fields initialized { myRollCount = 0; mySides = sides;}int Dice::NumSides() const// postcondition: return # of sides of die { return mySides;}A Computer Science Tapestry6.11More on method implementationEach method can access private data members of an object, so same method implementation shared by different objectscube.NumSides() compared to dodeca.NumSides()int Dice::NumSides() const// postcondition: return # of sides of die { return mySides;} int Dice::Roll()// postcondition: number of rolls updated// random 'die' roll returned { RandGen gen; // random number generator (“randgen.h”) myRollCount= myRollCount + 1; // update # of rolls return gen.RandInt(1,mySides); // in range [1..mySides]}A Computer Science Tapestry6.12Understanding Class ImplementationsYou do NOT need to understand implementations to write programs that use classesYou need to understand interfaces, not implementationsHowever, at some point you’ll write your own classesData members are global or accessible to each class methodConstructors should assign values to each instance
View Full Document