Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.

Similar presentations


Presentation on theme: "Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early."— Presentation transcript:

1 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

2 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.1 Abstract Data Types Programmer-created data types that specify –legal values that can be stored –operations that can be done on the values The user of an abstract data type (ADT) does not need to know any implementation details (e.g., how the data is stored or how the operations on it are carried out)

3 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Abstraction and Data Types Abstraction: a definition that captures general characteristics without details –An abstract triangle is a 3-sided polygon. A specific triangle may be scalene, isosceles, or equilateral Data Type: defines the kind of values that can be stored and the operations that can be performed on it

4 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.2 Object-Oriented Programming Procedural programming uses variables to store data, focuses on the processes/ functions that occur in a program. Data and functions are separate and distinct. Object-oriented programming is based on objects that encapsulate the data and the functions that operate on it.

5 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Object-Oriented Programming Terminology object: software entity that combines data and functions that act on the data in a single unit attributes: the data items of an object, stored in member variables member functions (methods): procedures/ functions that act on the attributes of the class

6 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley More Object-Oriented Programming Terminology data hiding: restricting access to certain members of an object. The intent is to allow only member functions to directly access and modify the object’s data encapsulation: the bundling of an object’s data and procedures into a single entity

7 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 7 Limitations of Procedural Programming If the data structures change, many functions must also be changed –Data and functions are separate entities As programs become larger and more complex, the separation of a program’s data and the code that operates on the data can lead to problems –difficult to understand and maintain –difficult to modify and extend –easy to break

8 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 8 Object Oriented Programming OOP programming is centered on creating objects –An object is a software entity that contains both data and procedures –Conceptually, it is a self-contained unit consisting of attributes (data) and procedures (methods or functions) The data is known as the object’s attributes The procedures that an object performs are called member methods or functions

9 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 9 Classes and Objects A class is like a blueprint (not real) and objects are like houses built from the blueprint (real things) –An object is an instance of a class

10 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Object Example Member variables (attributes) int side; Member functions void setSide(int s) { side = s; } int getSide() { return side; } Square Square object’s data item: side Square object’s functions: setSide - set the size of the side of the square, getSide - return the size of the side of the square

11 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.3 Introduction to Classes Class: a programmer-defined datatype used to define objects It is a pattern for creating objects Class declaration format: class className { declaration; }; Notice the required ;

12 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Access Specifiers Used to control access to members of the class. Each member is declared to be either public: can be accessed by functions outside of the class or private: can only be called by or accessed by functions that are members of the class

13 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Class Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; Access specifiers

14 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley More on Access Specifiers Can be listed in any order in a class Can appear multiple times in a class If not specified, the default is private

15 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.4 Introduction to Objects An object is an instance of a class Defined just like other variables Square sq1, sq2; Can access members using dot operator sq1.setSide(5); cout << sq1.getSide();

16 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Types of Member Functions Acessor, get, getter function: uses but does not modify a member variable ex: getSide Mutator, set, setter function: modifies a member variable ex: setSide

17 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.5 Defining Member Functions Member functions are part of a class declaration Can place entire function definition inside the class declaration or Can place just the prototype inside the class declaration and write the function definition after the class

18 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Defining Member Functions Inside the Class Declaration Member functions defined inside the class declaration are called inline functions Only very short functions, like the one below, should be inline functions int getSide() { return side; }

19 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Inline Member Function Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; inline functions

20 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Defining Member Functions After the Class Declaration Put a function prototype in the class declaration In the function definition, precede function name with class name and scope resolution operator ( :: ) int Square::getSide() { return side; }

21 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Conventions and a Suggestion Conventions: Member variables are usually private Accessor and mutator functions are usually public Use ‘get’ in the name of accessor functions, ‘set’ in the name of mutator functions Suggestion: calculate values to be returned in accessor functions when possible, to minimize the potential for stale data. For example, do not store area of the square in a variable but calculate it each time you refer to it as side may change.

22 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Tradeoffs of Inline vs. Regular Member Functions When a regular function is called, control passes to the called function –the compiler stores return address of call, allocates memory for local variables, etc. Code for an inline function is copied into the program in place of the call when the program is compiled –larger executable program, but –less function call overhead, possibly faster execution

23 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.6 Constructors A constructor is a member function that is used to initialize data members of a class Is called automatically when an object of the class is created Must be a public member function Must be named the same as the class Must have no return type, not even void

24 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Constructor – 2 Examples Inline: class Square {... public: Square(int s) { side = s; }... }; Declaration outside the class: Square(int); //prototype //in class Square::Square(int s) { side = s; }

25 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 25

26 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 26

27 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 27

28 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Overloading Constructors A class can have more than 1 constructor Overloaded constructors in a class must have different parameter lists Square(); Square(int);

29 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Default Constructor Constructors can have any number of parameters, including none A default constructor is one that takes no arguments either due to –No parameters or –All parameters have default values If a class has any programmer-defined constructors, it must have a programmer- defined default constructor

30 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Default Constructor Example class Square { private: int side; public: Square() // default { side = 1; } // constructor // Other member // functions go here }; Has no parameters

31 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Another Default Constructor Example class Square { private: int side; public: Square(int s = 1) // default { side = s; } // constructor // Other member // functions go here }; Has parameter but it has a default value

32 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Invoking a Constructor To create an object using the default constructor, use no argument list and no () Square square1; To create an object using a constructor that has parameters, include an argument list Square square1(8);

33 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.7 Destructors Public member function automatically called when an object is destroyed Destructor name is ~ className, e.g., ~Square Has no return type Takes no arguments Only 1 destructor is allowed per class (i.e., it cannot be overloaded)

34 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 34 Destructors Including a destructor prototype in Rectangle.h and function in Rectangle.cpp will cause the destructor to execute when main is complete This program will calculate the area of a rectangle. What is the width? 23 What is the length? 12 Here is the rectangle's data: Width: 23 Length: 12 Area: 276 Destructor is running

35 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7. 8 Private Member Functions A private member function can only be called by another member function of the same class It is used for internal processing by the class, not for use outside of the class

36 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.9 Passing Objects to Functions A class object can be passed as an argument to a function When passed by value, function makes a local copy of object. Original object in calling environment is unaffected by actions in function When passed by reference, function can use ‘set’ functions to modify the object.

37 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Notes on Passing Objects Using a value parameter for an object can slow down a program and waste space Using a reference parameter speeds up program, but allows the function to modify data in the structure To save space and time, while protecting structure data that should not be changed, use a const reference parameter void showData(const Square &s) // header

38 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning an Object from a Function A function can return an object Square initSquare(); // prototype s1 = initSquare(); // call Function must define a object –for internal use –to use with return statement

39 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning an Object Example Square initSquare() { Square s; // local variable int inputSize; cout << "Enter the length of side: "; cin >> inputSize; s.setSide(inputSize); return s; }

40 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.10 Object Composition Occurs when an object is a member variable of another object. Often used to design complex objects whose members are simpler objects ex. (from book): Define a rectangle class. Then, define a carpet class and use a rectangle object as a member of a carpet object.

41 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Object Composition, cont.

42 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Class Composition class Rectangle {private: double length; double width; public: void setLength(double len) { length = len; } void setWidth(double wid) { width = wid; } double getLength() { return length; } double getWidth() { return width; } double getArea() { return length * width; } }; class Carpet { private: double pricePerSqYd; Rectangle size; public: void setPricePerYd(double p) { pricePerSqYd = p; } void setDimensions(double len, double wid) { size.setLength(len/3); size.setWidth (wid/3); } double getTotalPrice() { return (size.getArea() * pricePerSqYd); } };

43 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Class Composition int main() { Carpet purchase; double pricePerYd; double length; double width; cout << "Room length in feet: "; cin >> length; cout << "Room width in feet : "; cin >> width; cout << "Carpet price per sq. yard: "; cin >> pricePerYd; purchase.setDimensions(length, width); purchase.setPricePerYd(pricePerYd); cout << "\nThe total price of my new " << length << " x " << width << " carpet is $" << purchase.getTotalPrice() << endl; return 0; }

44 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.11 Separating Class Specification, Implementation, and Client Code Separating class declaration, member function definitions, and the program that uses the class into separate files is considered good design

45 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using Separate Files Place class declaration in a header file that serves as the class specification file. Name the file classname.h ( for example, Square.h) Place member function definitions in a class implementation file. Name the file classname.cpp (for example, Square.cpp) This file should #include the class specification file. A client program (client code) that uses the class must #include the class specification file and be compiled and linked with the class implementation file.

46 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Separating Specification from Implementation Provides flexibility –A class can be given to another programmer without sharing the source code by providing the compiled object file for the class’s implementation The other programmer inserts the necessary #include directive into his program, compiles it and links it with your class’s object file –When a class’s member functions must be modified, it is only necessary to modify the implementation file and recompile it into a new object file Programs that use the class don’t have to be completely recompiled, just linked with the new object file

47 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Rectangle.h // Specification file for the Rectangle class. #ifndef RECTANGLE_H #define RECTANGLE_H // Rectangle class declaration. class Rectangle { private: double width; double length; public: void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; }; #endif This directive tells the preprocessor to see if a constant named RECTANGLE_H has not been previously created with a #define directive If the RECTANGLE_H constant has not been defined, these lines are included in the program. Otherwise, these lines are not included in the program The first included line defines the RECTANGLE_H constant. If this file is included again, the include guard will skip its contents

48 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Rectangle.h Preprocessor directives #ifndef and #endif –include guard – prevents the header file from accidentally being included more than once by an #include in a main Could have two includes, where second include specifies a.h files that the first include already specified #ifndef – if not defined

49 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Rectangle.cpp The implementation file contains the member functions of the class The first line is #include “Rectangle.h” –The filename is enclosed in double quotation marks; this indicates that the file is in the current project directory –The angled brackets are used to include files that are found in the compiler’s include file directory – this is where all of the standard C++ header files are located The remaining code consists of the member functions In Code::blocks or Dev C++ you can create a project with 3 separate files and then build and run the main program On UNIX you can compile all the cpp file on one line and then run the resulting executable g++ RectangleMain.cpp Rectangle.cpp –o RectangleRun You can also compile Rectangle cpp into an object file (Rectangle.o) once it is set using g++ -c Rectangle.cpp and then include it with the main on the full compile g++ -c RectangleMain.cpp Rectangle.o –o RectangleRun

50 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Rectangle Specification & Implementation // Rectangle.h #ifndef RECTANGLE_H #define RECTANGLE_H // Rectangle class declaration. class Rectangle { private: double width; double length; public: void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; }; #endif // RectangleMain.cpp // This program uses the Rectangle class, which is declared in // the Rectangle.h file. The member Rectangle class's member // functions are defined in the Rectangle.cpp file. This program // should be compiled with those files in a project. #include #include "Rectangle.h" // Needed for Rectangle class using namespace std; int main() { Rectangle box; // Define an instance of the Rectangle class double rectWidth; // Local variable for width double rectLength; // Local variable for length // Get the rectangle's width and length from the user. cout << "This program will calculate the area of a\n"; cout << "rectangle. What is the width? "; cin >> rectWidth; cout << "What is the length? "; cin >> rectLength; // Store the width and length of the rectangle // in the box object. box.setWidth(rectWidth); box.setLength(rectLength); // Display the rectangle's data. cout << "Here is the rectangle's data:\n"; cout << "Width: " << box.getWidth() << endl; cout << "Length: " << box.getLength() << endl; cout << "Area: " << box.getArea() << endl; return 0; }

51 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Rectangle Specification & Implementation // Rectangle.cpp #include "Rectangle.h" // Needed for the Rectangle class #include // Needed for cout #include // Needed for the exit function using namespace std; //*********************************************************** // setWidth sets the value of the member variable width. * //*********************************************************** void Rectangle::setWidth(double w) { if (w >= 0) width = w; else { cout << "Invalid width\n"; exit(EXIT_FAILURE); } //*********************************************************** // setLength sets the value of the member variable length. * //*********************************************************** void Rectangle::setLength(double len) { if (len >= 0) length = len; else { cout << "Invalid length\n"; exit(EXIT_FAILURE); } //*********************************************************** // getWidth returns the value in the member variable width. * //*********************************************************** double Rectangle::getWidth() const { return width; } //************************************************************* // getLength returns the value in the member variable length. * //************************************************************* double Rectangle::getLength() const { return length; } //************************************************************ // getArea returns the product of width times length. * //************************************************************ double Rectangle::getArea() const { return width * length; }

52 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Include Guards Used to prevent a header file from being included twice Format: #ifndef symbol_name #define symbol_name... (normal contents of header file) #endif symbol_name is usually the name of the header file, in all capital letters: #ifndef SQUARE_H #define SQUARE_H... #endif

53 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Rectangle Specification & Implementation Rectangle.cpp (Implementation file) Rectangle.h (Specification file) RectangleMain.cpp (Main Program file) RectangleMain.cpp is compiled Rectangle.h is included Rectangle.obj (Object file) RectangleMain.obj (Object file) Rectangle.h is included Rectangle.cpp is compiled RectangleMain.exe (Executable file) Rectangle.obj and RectangleMain.obj are linked and RectangleRun.exe is created

54 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley What Should Be Done Inside vs. Outside the Class Class should be designed to provide functions to store and retrieve data In general, I/O should be done by functions that use class objects, rather than by class member functions

55 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.12 Input Validation Objects Classes can be designed to validate user input –to ensure acceptable menu choice –to ensure a value is in range of valid values –etc.

56 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8.14 Arrays of Class Objects Class objects can also be used as array elements class Square { private: int side; public: Square(int s = 1) { side = s; } int getSide() { return side; } }; Square shapes[10]; // Create array of 10 // Square objects 8-56

57 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arrays of Class Objects Use an array subscript to access a specific object in the array Then use dot operator to access member methods of that object for (i = 0; i < 10; i++) cout << shapes[i].getSide() << endl; 8-57

58 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Initializing Arrays of Objects Can use default constructor to perform same initialization for all objects Can use initialization list to supply specific initial values for each object Square shapes[5] = {1,2,3,4,5}; Default constructor is used for the remaining objects if initialization list is too short Square boxes[5] = {1,2,3}; 8-58

59 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Initializing Arrays of Objects If an object is initialized with a constructor that takes more than one argument, the initialization list must include a call to the constructor for that object Rectangle spaces[3] = { Rectangle(2,5), Rectangle(1,3), Rectangle(7,7) }; Circle circle[3]={Circle (4.0,2,1), Circle(2.0,1,3), Circle(2.5,5,-1)}; It isn’t necessary to call the same constructor for each object in the array Circle cirlce[3]={4.0, Circle(2.0,1,3),2.5}; 8-59

60 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arrays of Objects #include #include "Circle.h" // Needed to create Circle objects using namespace std; const int NUM_CIRCLES = 4; int main() {Circle circle[NUM_CIRCLES]; for (int index = 0; index < NUM_CIRCLES; index++) { double r; cout << "Enter the radius for circle " << (index+1) << ": "; cin >> r; circle[index].setRadius(r); } cout << fixed << showpoint << setprecision(2); cout << "\nAreas of the " << NUM_CIRCLES<< " circles.\n"; for (int index = 0; index < NUM_CIRCLES; index++) { cout << "circle " << (index+1) << setw(8) << circle[index].findArea() << endl; } return 0; }

61 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arrays of Objects: Key Points The elements of an array can be objects If you do not use an initialization list when an array of objects is created, the default constructor will be invoked for each object in the array It is not necessary that all objects in the array use the same constructor If you do use an initialization list when an array of objects is created, the correct constructor will be called for each object, depending on the number and type of arguments used If a constructor requires more than one argument, the initializer must take the form of a constructor function call If there are fewer initializer calls in the list than there are objects in the array, the default constructor will be called for all the remaining objects It is best to always provide a default constructor; but if there is none you must be sure to furnish an initializer for every object in the array

62 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.15 Introduction to Object-Oriented Analysis and Design Object-Oriented Analysis: that phase of program development when the program functionality is determined from the requirements It includes –identification of objects and classes –definition of each class's attributes –identification of each class's behaviors –definition of the relationship between classes

63 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Identify Objects and Classes Consider the major data elements and the operations on these elements Candidates include –user-interface components (menus, text boxes, etc.) –I/O devices –physical objects –historical data (employee records, transaction logs, etc.) –the roles of human participants

64 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Finding the Classes Technique: Write a description of the problem domain (objects, events, etc. related to the problem) List the nouns, noun phrases, and pronouns. These are all candidate objects Refine the list to include only those objects that are relevant to the problem

65 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Define Class Attributes and Behaviors For each class, –determine the data elements needed by an object of that class –determine the behaviors or activities that the class must perform

66 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Determine Class Responsibilities Class responsibilities: What is the class responsible to know? What is the class responsible to do? Use these to define the member functions

67 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Relationships Between Classes Possible relationships –Access ("uses-a") –Ownership/Composition ("has-a") –Inheritance ("is-a")

68 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Object Reuse A well-defined class can be used to create objects in multiple programs By re-using an object definition, program development time is shortened One goal of object-oriented programming is to support object reuse

69 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 69 OOP Case Study You are a programmer for the Home Software Company. You have been assigned to develop a class that models the basic workings of a bank account. The class should perform the following tasks: Save the account balance. Save the number of transactions performed on the account. Allow deposits to be made to the account. Allow withdrawals to be taken from the account. Calculate interest for the period. Report the current account balance at any time.

70 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 70 OOP Case Study Private Member Variables needed by the class. VariableDescription balance A double that holds the current account balance. interestRate A double that holds the interest rate for the period interest A double that holds the interest earned for the current period. transactions An integer that holds the current number of transactions

71 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 71 OOP Case Study - Public Member Functions FunctionDescription Constructor Takes arguments to he initially stored in the balance and interestRate members. The default value for the balance is zero and the default value for the interest rate is 0.045. setInterestRate Takes a double argument which is stored in the interestRate member makeDeposit Takes a double argument, which is the amount of the deposit. This argument is added to balance. withdraw Takes a double argument which is the amount of the withdrawal. This value is subtracted from the balance, unless the withdrawal amount is greater than the balance. If this happens, the function reports an error. calcInterest Takes no arguments. This function calculates the amount of interest for the current period, stores this value in the interest member, and then adds it to the balance member. getInterestRate Returns the current interest rate (stored in the interestRate member). getBalance Returns the current balance (stored in the balance member). getInterest Returns the interest earned for the current period stored in the interest member). getTransactions Returns the number of transactions for the current period (stored in the transactions member).

72 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 72 Account.h #ifndef ACCOUNT_H #define ACCOUNT_H class Account { private: double balance; double interestRate; double interest; int transactions; public: Account(double iRate = 0.045, double bal = 0) { balance = bal; interestRate = iRate; interest = 0; transactions = 0; } void setInterestRate(double iRate) { interestRate = iRate; } void makeDeposit(double amount) { balance += amount; transactions++; } bool withdraw(double amount); // Defined in Account.cpp void calcInterest() { interest = balance * interestRate; balance += interest; } double getInterestRate() const { return interestRate; } double getBalance() const { return balance; } double getInterest() const { return interest; } int getTransactions() const { return transactions; } }; #endif

73 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 73 Account.cpp // Implementation file for the Account class. #include "Account.h" bool Account::withdraw(double amount) { if (balance < amount) return false; // Not enough in the account else { balance -= amount; transactions++; return true; }

74 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 74 The Unified Modeling Language UML stands for Unified Modeling Language. The UML provides a set of standard diagrams for graphically depicting object- oriented systems

75 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 75 UML Class Diagram A UML diagram for a class has three main sections.

76 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 76 Example: A Rectangle Class class Rectangle { private: double width; double length; public: bool setWidth(double); bool setLength(double); double getWidth() const; double getLength() const; double getArea() const; };

77 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 77 UML Access Specification Notation In UML you indicate a private member with a minus (-) and a public member with a plus(+). These member variables are private. These member functions are public.

78 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 78 UML Data Type Notation To indicate the data type of a member variable, place a colon followed by the name of the data type after the name of the variable. - width : double - length : double

79 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 79 UML Function Return Type Notation To indicate the data type of a function’s parameter variable, place a colon followed by the name of the data type after the name of the variable. To indicate the data type of a function’s return value, place a colon followed by the name of the data type after the function’s parameter list. + setWidth(w : double) : void + setWidth(w : double)

80 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 80 The Rectangle Class

81 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 81 Showing Constructors and Destructors Constructors Destructor No return type listed for constructors or destructors

82 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 82 Object Oriented Design Joe’s Automotive Shop service foreign cars and specializes in servicing cars made by Mercedes, Porsche and BMW. When a customer brings in a car to the shop, the manager gets the customer’s name, address and telephone number. The manager then determines the make, model and year of the car and gives the customer a service quote. The service quote shows the estimated part charges, estimated labor charges, sales tax and total estimated charges.

83 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 83 Object Oriented Design Finding the classes and their responsibilities –Get a written description of the problem domain The problem domain is the set of real-world objects, parties and major events related to the problem This may include: –Physical objects such as vehicles, machines or products –Any role played by a person, such as a manager, employer, customer, teacher, student, etc. –The results of a business event such as a customer order or service quote –Recordkeeping items such as customer histories and payroll records

84 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 84 Object Oriented Design –Identify all the nouns and noun phrases Address, BMW, car, cars, customer, estimated labor charges, foreign cars, model, name, Porsche, sales tax, Joe’s Automotive shop, telephone number, shop, … They are candidates to become classes, the list must be refined to include only those classes necessary to solve the problem Eliminate duplicate nouns –Cars/ foreign cars; Joe’s Automotive shop/shop Some nouns may not be needed in order to solve the problem –Shop, manager Some nouns might represent objects, not classes –Porsche. Mercedes, BMW, car Some nouns might represent simple values that can be stored in a variable and do not require a class. –If the answer to both of the following questions is NO, then the noun probably represents a value that can be stored in a simple variable »Would you use a group of related values to represent the item’s state? »Are there any obvious actions to be performed by the item? »Address, estimate labor charges, make model, name, sales tax, telephone number, year …

85 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 85 Object Oriented Design We are left with cars, customers and service quote as class candidates Next determine the Class’s Responsibilities –the things the class is responsible for knowing – these are the class’s attributes –The actions that the class is responsible for doing – these are the class’s member functions

86 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 86 Object Oriented Design

87 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 87 OOD Problem Domain Exercise The bank offers the following types of accounts to its customers: savings accounts, checking accounts, and money market accounts. Customers are allowed to deposit money into an account (thereby increasing its balance), withdraw money fruit an account (thereby decreasing its balance), and earn interest on the account. Each account has an interest rate. Assume that you are writing an application that will calculate the amount of interest earned for a bank account. a)Identify the potential classes in this problem domain. b)Refine the list to include only the necessary class or classes for this problem. c)Identify the responsibilities of the class or classes.

88 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C++: Classes & Objects - 1 88 OOD Example a)After eliminating duplicates, objects, and primitive values, the potential classes are: bank, account, and customer b)The only class needed for this particular problem is account. c)The account class knows its balance and interest rate. The account can calculate interest earned.

89 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.16 Screen Control Programs to date have all displayed output starting at the upper left corner of computer screen or output window. Output is displayed left-to-right, line-by-line. Computer operating systems are designed to allow programs to access any part of the computer screen. Such access is operating system-specific.

90 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Screen Control – Concepts An output screen can be thought of as a grid of 25 rows and 80 columns. Row 0 is at the top of the screen. Column 0 is at the left edge of the screen. The intersection of a row and a column is a cell. It can display a single character. A cell is identified by its row and column number. These are its coordinates.

91 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Screen Control – Windows - Specifics #include to access the operating system from a program Create a handle to reference the output screen: HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE); Create a COORD structure to hold the coordinates of a cell on the screen: COORD position;

92 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Screen Control – Windows – More Specifics Assign coordinates where the output should appear: position.X = 30; // column position.Y = 12; // row Set the screen cursor to this cell: SetConsoleCursorPosition(screen, position); Send output to the screen: cout << "Look at me!" << endl; –be sure to end with endl, not '\n' or nothing

93 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

94 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7.13 Structures Structure: C++ construct that allows multiple variables to be grouped together Structure Declaration Format: struct structure name { type1 field1; type2 field2; … typen fieldn; };

95 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example struct Declaration struct Student { int studentID; string name; short year; double gpa; } ; structure tag structure members Notice the required ;

96 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley struct Declaration Notes struct names commonly begin with an uppercase letter The structure name is also called the tag Multiple fields of same type can be in a comma-separated list string name, address;

97 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Defining Structure Variables struct declaration does not allocate memory or create variables To define variables, use structure tag as type name Student s1; studentID name year gpa s1

98 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Accessing Structure Members Use the dot (.) operator to refer to members of struct variables getline(cin, s1.name); cin >> s1.studentID; s1.gpa = 3.75; Member variables can be used in any manner appropriate for their data type

99 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Displaying struct Members To display the contents of a struct variable, you must display each field separately, using the dot operator Wrong: cout << s1; // won’t work! Correct: cout << s1.studentID << endl; cout << s1.name << endl; cout << s1.year << endl; cout << s1.gpa;

100 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Comparing struct Members Similar to displaying a struct, you cannot compare two struct variables directly: if (s1 >= s2) // won’t work! Instead, compare member variables: if (s1.gpa >= s2.gpa) // better

101 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Initializing a Structure Cannot initialize members in the structure declaration, because no memory has been allocated yet struct Student // Illegal { // initialization int studentID = 1145; string name = "Alex"; short year = 1; float gpa = 2.95; };

102 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Initializing a Structure (continued) Structure members are initialized at the time a structure variable is created Can initialize a structure variable’s members with either –an initialization list –a constructor

103 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using an Initialization List An initialization list is an ordered set of values, separated by commas and contained in { }, that provides initial values for a set of data members {12, 6, 3} // initialization list // with 3 values

104 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley More on Initialization Lists Order of list elements matters: First value initializes first data member, second value initializes second data member, etc. Elements of an initialization list can be constants, variables, or expressions {12, W, L/W + 1} // initialization list // with 3 items

105 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Initialization List Example Structure Declaration Structure Variable struct Dimensions { int length, width, height; }; Dimensions box = {12,6,3}; box length12 width 6 height3

106 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Partial Initialization Can initialize just some members, but cannot skip over members Dimensions box1 = {12,6}; //OK Dimensions box2 = {12,,3}; //illegal

107 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Problems with Initialization List Can’t omit a value for a member without omitting values for all following members Does not work on most modern compilers if the structure contains any string objects –Will, however, work with C-string members

108 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using a Constructor to Initialize Structure Members Similar to a constructor for a class: –name is the same as the name of the struct –no return type –used to initialize data members It is normally written inside the struct declaration

109 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A Structure with a Constructor struct Dimensions { int length, width, height; // Constructor Dimensions(int L, int W, int H) {length = L; width = W; height = H;} };

110 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Passing Arguments to a Constructor Create a structure variable and follow its name with an argument list Example: Dimensions box3(12, 6, 3);

111 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Nested Structures A structure can have another structure as a member. struct PersonInfo { string name, address, city; }; struct Student { int studentID; PersonInfo pData; short year; double gpa; };

112 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Members of Nested Structures Use the dot operator multiple times to access fields of nested structures Student s5; s5.pData.name = "Joanne"; s5.pData.city = "Tulsa";

113 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Structures as Function Arguments May pass members of struct variables to functions computeGPA(s1.gpa); May pass entire struct variables to functions showData(s5); Can use reference parameter if function needs to modify contents of structure variable

114 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Notes on Passing Structures Using a value parameter for structure can slow down a program and waste space Using a reference parameter speeds up program, but allows the function to modify data in the structure To save space and time, while protecting structure data that should not be changed, use a const reference parameter void showData(const Student &s) // header

115 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning a Structure from a Function Function can return a struct Student getStuData(); // prototype s1 = getStuData(); // call Function must define a local structure variable –for internal use –to use with return statement

116 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Returning a Structure Example Student getStuData() { Student s; // local variable cin >> s.studentID; cin.ignore(); getline(cin, s.pData.name); getline(cin, s.pData.address); getline(cin, s.pData.city); cin >> s.year; cin >> s.gpa; return s; }

117 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Unions Similar to a struct, but – all members share a single memory location, which saves space – only 1 member of the union can be used at a time Declared using key word union Otherwise the same as struct Variables defined and accessed like struct variables

118 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example union Declaration union WageInfo { double hourlyRate; float annualSalary; }; union tag Notice the required ; union members


Download ppt "Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early."

Similar presentations


Ads by Google