Presentation is loading. Please wait.

Presentation is loading. Please wait.

Starting Out with C++ 2nd Edition, by Tony Gaddis 1 Chapter 7 – Classes and Structured Data.

Similar presentations


Presentation on theme: "Starting Out with C++ 2nd Edition, by Tony Gaddis 1 Chapter 7 – Classes and Structured Data."— Presentation transcript:

1 Starting Out with C++ 2nd Edition, by Tony Gaddis 1 Chapter 7 – Classes and Structured Data

2 Starting Out with C++ 2nd Edition, by Tony Gaddis 2 7.1 Abstract data types Abstract data types (ADTs) are data types created by the programmer. ADTs have their own range (or domain) of data and their own set of operations that may be performed on them.

3 Starting Out with C++ 2nd Edition, by Tony Gaddis 3 Abstraction An abstraction is a general model of something.

4 Starting Out with C++ 2nd Edition, by Tony Gaddis 4 Data Types C++ has several primitive data types: Table 7-1

5 Starting Out with C++ 2nd Edition, by Tony Gaddis 5 Abstract Data Types A data type created by the programmer –The programmer decides what values are acceptable for the data type –The programmer decides what operations may be performed on the data type

6 Starting Out with C++ 2nd Edition, by Tony Gaddis 6 7.2 Focus on Software Engineering: Combining Data into Structures C++ allows you to group several variables together into a single item known as a structure.

7 Starting Out with C++ 2nd Edition, by Tony Gaddis 7 Table 7-2

8 Starting Out with C++ 2nd Edition, by Tony Gaddis 8 Table 7-2 As a Structure: struct PayRoll { int empNumber; char name[25]; float hours; float payRate; float grossPay; };

9 Starting Out with C++ 2nd Edition, by Tony Gaddis 9 Figure 7-1 empNumber name hours payRate grossPay deptHead Structure Variable Name Members

10 Starting Out with C++ 2nd Edition, by Tony Gaddis 10 Figure 7-2 empNumber name hours payRate grossPay deptHead empNumber name hours payRate grossPay foreman empNumber name hours payRate grossPay associate

11 Starting Out with C++ 2nd Edition, by Tony Gaddis 11 Two steps to implementing structures: Create the structure declaration. This establishes the tag (or name) of the structure and a list of items that are members. Declare variables (or instances) of the structure and use them in the program to hold data.

12 Starting Out with C++ 2nd Edition, by Tony Gaddis 12 7.3 Accessing Structure Members The dot operator (.) allows you to access structure members in a program

13 Starting Out with C++ 2nd Edition, by Tony Gaddis 13 Program 7-1 // This program demonstrates the use of structures. #include using namespace std; struct PayRoll { int empNumber;// Employee number char name[25];// Employee's name float hours;// hours worked float payRate;// Hourly Payrate float grossPay;// Gross Pay };

14 Starting Out with C++ 2nd Edition, by Tony Gaddis 14 Program continues int main() { PayRoll employee;// Employee is a PayRoll structure cout << "Enter the employee's number: "; cin >> employee.empNumber; cout << "Enter the employee's name: "; cin.ignore();// To skip the remaining '\n' character cin.getline(employee.name, 25); cout << "How many hours did the employee work? "; cin >> employee.hours; cout << "What is the employee's hourly payrate? "; cin >> employee.payRate; employee.grossPay = employee.hours * employee.payRate; cout << "Here is the employee's payroll data:\n"; cout << "Name: " << employee.name << endl;

15 Starting Out with C++ 2nd Edition, by Tony Gaddis 15 Program continues cout << "Number: " << employee.empNumber << endl; cout << "hours worked: " << employee.hours << endl; cout << "Hourly Payrate: " << employee.payRate << endl; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "Gross Pay: $" << employee.grossPay << endl; return 0; }

16 Starting Out with C++ 2nd Edition, by Tony Gaddis 16 Program Output with Example input Enter the employee's number: 489 [Enter] Enter the employee's name: Jill Smith [Enter] How many hours did the employee work? 40 [Enter] What is the employee's hourly payrate? 20 [Enter] Here is the employee's payroll data: Name: Jill Smith Number: 489 hours worked: 40 Hourly Payrate: 20 Gross Pay: $800.00

17 Starting Out with C++ 2nd Edition, by Tony Gaddis 17 Displaying a Structure The contents of a structure variable cannot be displayed by passing the entire variable to cout. For example, assuming employee is a PayRoll structure variable, the following statement will not work: cout << employee << endl; //won’t work!

18 Starting Out with C++ 2nd Edition, by Tony Gaddis 18 Program 7-2 // This program uses a structure to hold // geometric data about a circle. #include #include // For the pow function using namespace std; struct Circle { float radius; float diameter; float area; }; const float pi = 3.14159;

19 Starting Out with C++ 2nd Edition, by Tony Gaddis 19 Program continues int main() { Circle c; cout << "Enter the diameter of a circle: "; cin >> c.diameter; c.radius = c.diameter / 2; c.area = pi * pow(c.radius, 2.0); cout << "The radius and area of the circle are:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "Radius: " << c.radius << endl; cout << "area: " << c.area << endl; return 0; }

20 Starting Out with C++ 2nd Edition, by Tony Gaddis 20 Program Output with Example input Enter the diameter of a circle: 10 [Enter] The radius and area of the circle are: Radius: 5 area: 78.54

21 Starting Out with C++ 2nd Edition, by Tony Gaddis 21 7.4 Initializing a Structure The members of a structure variable may be initialized with starting values when the structure variable is declared. struct GeoInfo { char cityName[30], state[3]; long population; int distance; }; GeoInfo location = {“Ashville”, “NC”, 50000, 28};

22 Starting Out with C++ 2nd Edition, by Tony Gaddis 22 7.5 Focus on Software Engineering: Nested Structures It’s possible for a structure variable to be a member of another structure variable. struct Costs { float wholesale; float retail; }; struct Item { char partNum[10], description[25]; Costs pricing; };

23 Starting Out with C++ 2nd Edition, by Tony Gaddis 23 7.6 Structures as Function Arguments Structure variables may be passed as arguments to functions.

24 Starting Out with C++ 2nd Edition, by Tony Gaddis 24 Figure 7-3 void showRect(Rectangle r) { cout << r.length << endl; cout << r.width << endl; cout << r.area << endl; } showRect(box);

25 Starting Out with C++ 2nd Edition, by Tony Gaddis 25 Program 7-3 // This program demonstrates a function that accepts // a structure variable as its argument. #include using namespace std; struct InvItem { int partNum;// Part number char description[50]; // Item description int onHand;// Units on hand float price;// Unit price }; void showItem(InvItem);// Function prototype

26 Starting Out with C++ 2nd Edition, by Tony Gaddis 26 Program continues int main() { InvItem part = {171, "Industrial Widget", 25, 150.0}; showItem(part); return 0; } // Definition of function showItem. This function accepts // an argument of the InvItem structure type. The contents // of the structure is displayed. void showItem(InvItem piece) { cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "Part Number: " << piece.partNum << endl; cout << "Description: " << piece.description << endl; cout << "Units On Hand: " << piece.onHand << endl; cout << "Price: $" << piece.price << endl; }

27 Starting Out with C++ 2nd Edition, by Tony Gaddis 27 Program Output Part Number: 171 Description: Industrial Widget Units On Hand: 25 Price: $150.00

28 Starting Out with C++ 2nd Edition, by Tony Gaddis 28 Program 7-4 // This program has a function that uses a structure reference variable // as its parameter. #include using namespace std; struct InvItem { int partNum;// Part number char description[50]; // Item description int onHand;// Units on hand float price;// Unit price }; // Function Prototypes void getItem(InvItem&); void showItem(InvItem);

29 Starting Out with C++ 2nd Edition, by Tony Gaddis 29 Program continues int main() { InvItem part; getItem(part); showItem(part); return 0; } // Definition of function getItem. This function uses a // structure reference variable as its parameter. It asks the // user for information to store in the structure. void getItem(InvItem &piece) { cout << "Enter the part number: "; cin >> piece.partNum; cout << "Enter the part description: "; cin.get(); // Eat the remaining newline cin.getline(piece.description, 50);

30 Starting Out with C++ 2nd Edition, by Tony Gaddis 30 Program continues cout << "Enter the quantity on hand: "; cin >> piece.onHand; cout << "Enter the unit price: "; cin >> piece.price; } // Definition of function showItem. This function accepts // an argument of the InvItem structure type. The contents // of the structure is displayed. void showItem(InvItem piece) { cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "Part Number: " << piece.partNum << endl; cout << "Description: " << piece.description << endl; cout << "Units On Hand: " << piece.onHand << endl; cout << "Price: $" << piece.price << endl; }

31 Starting Out with C++ 2nd Edition, by Tony Gaddis 31 Program Output Enter the part number: 800 [Enter] Enter the part description: Screwdriver [Enter] Enter the quantity on hand: 135 [Enter] Enter the unit price: 1.25 [Enter] Part Number: 800 Description: Screwdriver Units On Hand: 135 Price: $1.25

32 Starting Out with C++ 2nd Edition, by Tony Gaddis 32 Constant Reference Parameters Sometimes structures can be quite large. Therefore, passing by value can decrease a program’s performance. But passing by reference can cause problems. Instead, pass by constant reference: void showItem(const InvItem &piece) { cout.setf(ios::precision(2)|ios::fixed|ios::showpoint); cout << “Part Number: “ << piece.partNum << endl; cout << “Price: $” << piece.price << endl; }

33 Starting Out with C++ 2nd Edition, by Tony Gaddis 33 11.8 Returning a Structure from a Function A function may return a structure. struct Circle { float radius, diameter, area; }; Circle getData() { Circle temp; temp.radius = 10.0; temp.diameter = 20.0; temp.area = 314.159; return temp; }

34 Starting Out with C++ 2nd Edition, by Tony Gaddis 34 Program 7-5 // This program uses a function to return a structure. This // is a modification of Program 11-2. #include #include // For the pow function using namespace std; // Circle structure declaration struct Circle { float radius; float diameter; float area; };

35 Starting Out with C++ 2nd Edition, by Tony Gaddis 35 Program continues // Function prototype Circle getInfo(); // Constant definition for Pi const float pi = 3.14159; int main() { Circle c; c = getInfo(); c.area = pi * pow(c.radius, 2.0); cout << "The radius and area of the circle are:\n"; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "Radius: " << c.radius << endl; cout << "area: " << c.area << endl; return 0; }

36 Starting Out with C++ 2nd Edition, by Tony Gaddis 36 Program continues // Definition of function getInfo. This function uses a // local variable, round, which is a Circle structure. // The user enters the diameter of the circle, which is // stored in round.diameter. The function then calculates // the radius, which is stored in round.radius. round is then // returned from the function. Circle getInfo() { Circle round; cout << "Enter the diameter of a circle: "; cin >> round.diameter; round.radius = round.diameter / 2; return round; }

37 Starting Out with C++ 2nd Edition, by Tony Gaddis 37 Program Output with Example input Enter the diameter of a circle: 10 [Enter] The radius and area of the circle are: Radius: 5.00 area: 78.54

38 Starting Out with C++ 2nd Edition, by Tony Gaddis 38 7.8 Unions A union is like a structure, except all the members occupy the same memory area. Figure 7-4 employee1 : a PaySource union variable 1 st two bytes are used by hours, a short All four bytes are used by sales, a float

39 Starting Out with C++ 2nd Edition, by Tony Gaddis 39 Program 7-6 // This program demonstrates a union. #include using namespace std; union PaySource { short hours; float sales; }; int main() { PaySource employee1; char payType; float payRate, grossPay;

40 Starting Out with C++ 2nd Edition, by Tony Gaddis 40 Program continues cout.precision(2); cout.setf(ios::showpoint); cout << "This program calculates either hourly wages or\n"; cout << "sales commission.\n"; cout << "Enter H for hourly wages or C for commission: "; cin >> payType; if (toupper(payType) == 'H') { cout << "What is the hourly pay rate? "; cin >> payRate; cout << "How many hours were worked? "; cin >> employee1.hours; grossPay = employee1.hours * payRate; cout << "Gross pay: $" << grossPay << endl; }

41 Starting Out with C++ 2nd Edition, by Tony Gaddis 41 Program continues else if (payType == 'C') { cout << "What are the total sales for this employee? "; cin >> employee1.sales; grossPay = employee1.sales * 0.10; cout << "Gross pay: $" << grossPay << endl; } else { cout << payType << " is not a valid selection.\n"; } return 0; }

42 Starting Out with C++ 2nd Edition, by Tony Gaddis 42 Program Output with Example input This program calculates either hourly wages or sales commission. Enter H for hourly wages or C for commission: C [Enter] What are the total sales for this employee? 5000 [Enter] Gross pay: $500.00

43 Starting Out with C++ 2nd Edition, by Tony Gaddis 43 Anonymous Unions The members of an anonymous union have names, but the union itself has no name. union { member declarations;... };

44 Starting Out with C++ 2nd Edition, by Tony Gaddis 44 Program 7-7 // This program demonstrates an anonymous union. #include using namespace std; int main() { union// Anonymous union { short hours; float sales; }; char payType; float payRate, grossPay;

45 Starting Out with C++ 2nd Edition, by Tony Gaddis 45 Program continues cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "This program calculates either hourly wages or\n"; cout << "sales commission.\n"; cout << "Enter H for hourly wages or C for commission: "; cin >> payType; if (payType == 'H') { cout << "What is the hourly pay rate? "; cin >> payRate; cout << "How many hours were worked? "; cin >> hours; // Anonymous union member grossPay = hours * payRate; cout << "Gross pay: $" << grossPay << endl; }

46 Starting Out with C++ 2nd Edition, by Tony Gaddis 46 Program continues else if (payType == 'C') { cout << "What are the total sales for this employee? "; cin >> sales;// Anonymous union member grossPay = sales * 0.10; cout << "Gross pay: $" << grossPay << endl; } else { cout << payType << " is not a valid selection.\n"; } return 0; }

47 Starting Out with C++ 2nd Edition, by Tony Gaddis 47 Program Output with Example input This program calcualtes either hourly wages or sales commission. Enter H for hourly wages or C for commission: C [Enter] What are the total sales for the employee? 12000 [Enter] Gross pay: $1200.00

48 Starting Out with C++ 2nd Edition, by Tony Gaddis 48 7.9 Procedural and Object-Oriented Programming Procedural programming is a method of writing software. It is a programming practice centered on the procedures, or actions that take place in a program. Object-Oriented programming is centered around the object. Objects are created form abstract data types that encapsulate data and functions together.

49 Starting Out with C++ 2nd Edition, by Tony Gaddis 49 What’s Wrong with Procedural Programming? Programs with excessive global data Complex and convoluted programs Programs that are difficult to modify and extend

50 Starting Out with C++ 2nd Edition, by Tony Gaddis 50 What is Object-Oriented Programming? OOP is centered around the object, which packages together both the data and the functions that operate on the data.

51 Starting Out with C++ 2nd Edition, by Tony Gaddis 51 Figure 7-5 Member Variables float width; float length; float area; Member Functions void setData(float w, float l) { … function code … } void calcArea() { … function code … } void getWidth() { … function code … } void getLength() { … function code … } void getArea() { … function code … }

52 Starting Out with C++ 2nd Edition, by Tony Gaddis 52 Terminology In OOP, an object’s member variables are often called its attributes and its member functions are sometimes referred to as its behaviors or methods.

53 Starting Out with C++ 2nd Edition, by Tony Gaddis 53 Figure 7-6

54 Starting Out with C++ 2nd Edition, by Tony Gaddis 54 How are Objects Used? Although the use of objects is only limited by the programmer’s imagination, they are commonly used to create data types that are either very specific or very general in purpose.

55 Starting Out with C++ 2nd Edition, by Tony Gaddis 55 General Purpose Objects –Creating data types that are improvements on C++’s built-in data types. For example, an array object could be created that works like a regular array, but additionally provides bounds-checking. –Creating data types that are missing from C++. For instance, an object could be designed to process currencies or dates as if they were built-in data types. –Creating objects that perform commonly needed tasks, such as input validation and screen output in a graphical user interface.

56 Starting Out with C++ 2nd Edition, by Tony Gaddis 56 Application-Specific Objects Data types created for a specific application. For example, in an inventory program.

57 Starting Out with C++ 2nd Edition, by Tony Gaddis 57 7.10 Introduction to the Class In C++, the class is the construct primarily used to create objects. class class-name { declaration statements here };

58 Starting Out with C++ 2nd Edition, by Tony Gaddis 58 Example: class Rectangle { private: float width, length, area; public: void setData(float, float); void calcArea(); float getWidth(); float getLength(); float getArea(); };

59 Starting Out with C++ 2nd Edition, by Tony Gaddis 59 Access Specifiers The key words private and public are access specifiers. private means they can only be accessed by the member functions. public means they can be called from statements outside the class. –Note: the default access of a class is private, but it is still a good idea to use the private key word to explicitly declare private members. This clearly documents the access specification of the class.

60 Starting Out with C++ 2nd Edition, by Tony Gaddis 60 7.11 Defining Member Functions Class member functions are defined similarly to regular functions. void Rectangle::setData(float w, float l) { width = w; length = l; }

61 Starting Out with C++ 2nd Edition, by Tony Gaddis 61 continued from previous slide void rectangle::calcArea() { area = width * length; } etc. for all remaining member functions

62 Starting Out with C++ 2nd Edition, by Tony Gaddis 62 7.12 Defining an Instance of a Class Class objects must be defined after the class is declared. Defining a class object is called the instantiation of a class. Rectangle box; // box is an instance // of Rectangle

63 Starting Out with C++ 2nd Edition, by Tony Gaddis 63 Accessing an Object’s Members box.setData(10.0, 12.0) box.calcArea(); cout << box.getWidth(); cout << box.getLength(); cout << box.getArea();

64 Starting Out with C++ 2nd Edition, by Tony Gaddis 64 Program 7-8 // This program demonstrates a simple class. #include using namespace std; // Rectangle class declaration. class Rectangle { private: float width; float length; float area; public: void setData(float, float); void calcArea(); float getWidth(); float getLength(); float getArea(); };

65 Starting Out with C++ 2nd Edition, by Tony Gaddis 65 Program continues // setData copies the argument w to private member // width andl to private member length. void Rectangle::setData(float w, float l) { width = w; length = l; } // calcArea multiplies the private members width // and length. The result is stored in the private // member area. void Rectangle::calcArea() { area = width * length; }

66 Starting Out with C++ 2nd Edition, by Tony Gaddis 66 Program continues // getWidth returns the value in the private member width. float Rectangle::getWidth() { return width; } // getLength returns the value in the private member length. float Rectangle::getLength() { return length; } // getArea returns the value in the private member area. float Rectangle::getArea() { return area; }

67 Starting Out with C++ 2nd Edition, by Tony Gaddis 67 Program continues int main() { Rectangle box; float wide, boxLong; cout << "This program will calculate the area of a\n"; cout << "rectangle. What is the width? "; cin >> wide; cout << "What is the length? "; cin >> boxLong; box.setData(wide, boxLong); box.calcArea(); 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; }

68 Starting Out with C++ 2nd Edition, by Tony Gaddis 68 Program Output This program will calculate the area of a rectangle. What is the width? 10 [Enter] What is the length? 5 [Enter] Here is the rectangle's data: width: 10 length: 5 area: 50

69 Starting Out with C++ 2nd Edition, by Tony Gaddis 69 7.13 Why Have Private Members? In object-oriented programming, an object should protect its important data by making it private and providing a public interface to access that data.

70 Starting Out with C++ 2nd Edition, by Tony Gaddis 70 7.14 Focus on Software Engineering: Some Design Considerations Usually class declarations are stored in their own header files. Member function definitions are stored in their own.cpp files. The #ifndef directive allows a program to be conditionally compiled. This prevents a header file from accidentally being included more than once.

71 Starting Out with C++ 2nd Edition, by Tony Gaddis 71 Program 7-9 Contents of rectang.h #ifndef RECTANGLE_H #define RECTANGLE_H // Rectangle class declaration. class Rectangle { private: float width; float length; float area; public: void setData(float, float); void calcArea(); float getWidth(); float getLength(); float getArea(); }; #endif

72 Starting Out with C++ 2nd Edition, by Tony Gaddis 72 Contents of rectang.cpp #include "rectang.h" // setData copies the argument w to private member // width and l to private member length. void Rectangle::setData(float w, float l) { width = w; length = l; } // calcArea multiplies the private members width // and length. The result is stored in the private // member area. void Rectangle::calcArea() { area = width * length; }

73 Starting Out with C++ 2nd Edition, by Tony Gaddis 73 Program continues // getWidth returns the value in the private member width. float Rectangle::getWidth() { return width; } // getLength returns the value in the private member length. float Rectangle::getLength() { return length; } // getArea returns the value in the private member area. float Rectangle::getArea() { return area; }

74 Starting Out with C++ 2nd Edition, by Tony Gaddis 74 Program continues Contents of the main program, pr7-9.cpp // This program demonstrates a simple class. #include #include "rectang.h" // contains Rectangle class declaration using namespace std; // Don't forget to link this program with rectang.cpp! int main() { Rectangle box; float wide, boxLong; cout << "This program will calculate the area of a\n"; cout << "rectangle. What is the width? "; cin >> wide; cout << "What is the length? "; cin >> boxLong;

75 Starting Out with C++ 2nd Edition, by Tony Gaddis 75 Program continues box.setData(wide, boxLong); box.calcArea(); cout << "Here rectangle's data:\n"; cout << "width: " << box.getWidth() << endl; cout << "length: " << box.getLength() << endl; cout << "area: " << box.getArea() << endl; return 0; }

76 Starting Out with C++ 2nd Edition, by Tony Gaddis 76 Performing I/O in a Class Object Notice that the Rectangle example has no cin or cout. This is so anyone who writes a program that uses the Rectangle class will not be “locked into” the way the class performs input or output. Unless a class is specifically designed to perform I/O, operations like user input and output are best left to the person designing the application.

77 Starting Out with C++ 2nd Edition, by Tony Gaddis 77 Table 7-3

78 Starting Out with C++ 2nd Edition, by Tony Gaddis 78 7.15 Focus on Software Engineering: Using Private Member Functions A private member function may only be called from a function that is a member of the same object.

79 Starting Out with C++ 2nd Edition, by Tony Gaddis 79 Program 7-10 #include #include "rectang2.h" // contains Rectangle class declaration // Don't forget to link this program with rectang2.cpp! using namespace std; int main() { Rectangle box; float wide, boxLong; cout << "This program will calculate the area of a\n"; cout << "rectangle. What is the width? "; cin >> wide; cout << "What is the length? "; cin >> boxLong; box.setData(wide, boxLong); cout << "Here rectangle's data:\n"; cout << "width: " << box.getWidth() << endl; cout << "length: " << box.getLength() << endl; cout << "area: " << box.getArea() << endl; return 0; }

80 Starting Out with C++ 2nd Edition, by Tony Gaddis 80 Program Output This program will calculate the area of a rectangle. What is the width? 10 [Enter] What is the length? 5 [Enter] Here rectangle's data: width: 10 length: 5 area: 50

81 Starting Out with C++ 2nd Edition, by Tony Gaddis 81 13.9 Inline Member Functions When the body of a member function is defined inside a class declaration, it is declared inline.

82 Starting Out with C++ 2nd Edition, by Tony Gaddis 82 Program 7-11 Contents of rectang3.h #ifndef RECTANGLE_H #define RECTANGLE_H // Rectangle class declaration. class Rectangle { private: float width; float length; float area; void calcArea() { area = width * length; }

83 Starting Out with C++ 2nd Edition, by Tony Gaddis 83 Program continues public: void setData(float, float); // Prototype float getWidth() { return width; } float getLength() { return length; } float getArea() { return area; } }; #endif Contents of rectang3.cpp #include "rectang3.h" // setData copies the argument w to private member // width and l to private member length. void Rectangle::setData(float w, float l) { width = w; length = l; calcArea(); }

84 Starting Out with C++ 2nd Edition, by Tony Gaddis 84 Program continues Contents of the main program, PR7-11.CPP #include #include "rectang3.h" // contains Rectangle class declaration using namespace std; // Don't forget to link this program with rectang3.cpp! int main() { Rectangle box; float wide, boxLong; cout << "This program will calculate the area of a\n"; cout << "rectangle. What is the width? "; cin >> wide; cout << "What is the length? "; cin >> boxLong;

85 Starting Out with C++ 2nd Edition, by Tony Gaddis 85 Program continues box.setData(wide, boxLong); cout << "Here rectangle's data:\n"; cout << "width: " << box.getWidth() << endl; cout << "length: " << box.getLength() << endl; cout << "area: " << box.getArea() << endl; return 0; }

86 Starting Out with C++ 2nd Edition, by Tony Gaddis 86 Program Output This program will calculate the area of a rectangle. What is the width? 10 [Enter] What is the length? 5 [Enter] Here rectangle's data: width: 10 length: 5 area: 50

87 Starting Out with C++ 2nd Edition, by Tony Gaddis 87 7.17 Constructors A constructor is a member function that is automatically called when a class object is created. Constructors have the same name as the class. Constructors must be declared publicly. Constructors have no return type.

88 Starting Out with C++ 2nd Edition, by Tony Gaddis 88 Program 7-12 // This program demonstrates a constructor. #include using namespace std; class Demo { public: Demo();// Constructor }; Demo::Demo() { cout << "Welcome to the constructor!\n"; }

89 Starting Out with C++ 2nd Edition, by Tony Gaddis 89 Program continues int main() { Demo demoObj;// Declare a Demo object; cout << "This program demonstrates an object\n"; cout << "with a constructor.\n"; return 0; }

90 Starting Out with C++ 2nd Edition, by Tony Gaddis 90 Program Output Welcome to the constructor. This program demonstrates an object with a constructor.

91 Starting Out with C++ 2nd Edition, by Tony Gaddis 91 Program 7-13 // This program demonstrates a constructor. #include using namespace std; class Demo { public: Demo(); // Constructor }; Demo::Demo() { cout << "Welcome to the constructor!\n"; }

92 Starting Out with C++ 2nd Edition, by Tony Gaddis 92 Program continues int main() { cout << "This is displayed before the object\n"; cout << "is declared.\n\n"; Demo demoObj; cout << "\nThis is displayed after the object\n"; cout << "is declared.\n"; return 0; }

93 Starting Out with C++ 2nd Edition, by Tony Gaddis 93 Program Output This is displayed before the object is declared. Welcome to the constructor. This is displayed after the object is declared.

94 Starting Out with C++ 2nd Edition, by Tony Gaddis 94 Constructor Arguments When a constructor does not have to accept arguments, it is called an object’s default constructor. Like regular functions, constructors may accept arguments, have default arguments, be declared inline, and be overloaded.

95 Starting Out with C++ 2nd Edition, by Tony Gaddis 95 7 - 18 Destructors A destructor is a member function that is automatically called when an object is destroyed. –Destructors have the same name as the class, preceded by a tilde character (~) –In the same way that a constructor is called then the object is created, the destructor is automatically called when the object is destroyed. –In the same way that a constructor sets things up when an object is created, a destructor performs shutdown procedures when an object is destroyed.

96 Starting Out with C++ 2nd Edition, by Tony Gaddis 96 Program 7-14 // This program demonstrates a constructor & destructor #include using namespace std; class Demo { public: Demo(); // Constructor ~Demo(); // Destructor }; Demo::Demo() { cout << "Welcome to the constructor!\n"; }

97 Starting Out with C++ 2nd Edition, by Tony Gaddis 97 Program continues Demo::~Demo() { cout << "The destructor is now running.\n"; } int main() { Demo demoObj;// Declare a Demo object; cout << "This program demonstrates an object\n"; cout << "with a constructor and destructor.\n"; return 0; }

98 Starting Out with C++ 2nd Edition, by Tony Gaddis 98 Program Output Welcome to the constructor! This program demonstrates an object with a constructor and destructor. The destructor is now running.

99 Starting Out with C++ 2nd Edition, by Tony Gaddis 99 7.19 Constructors that Accept Arguments Information can be passed as arguments to an object’s constructor.

100 Starting Out with C++ 2nd Edition, by Tony Gaddis 100 Program 7-15 Contents of sale.h #ifndef SALE_H #define SALE_H // Sale class declaration class Sale { private: float taxRate; float total; public: Sale(float rate) { taxRate = rate; } void calcSale(float cost) { total = cost + (cost * taxRate) }; float getTotal() { return total; } }; #endif

101 Starting Out with C++ 2nd Edition, by Tony Gaddis 101 Program continues Contents of main program, pr7-15.cpp #include #include "sale.h" using namespace std; int main() { Sale cashier(0.06);// 6% sales tax rate float amnt; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "Enter the amount of the sale: "; cin >> amnt; cashier.calcSale(amnt); cout << "The total of the sale is $"; cout << cashier.getTotal << endl; return 0; }

102 Starting Out with C++ 2nd Edition, by Tony Gaddis 102 Program Output Enter the amount of the sale: 125.00 The total of the sale is $132.50

103 Starting Out with C++ 2nd Edition, by Tony Gaddis 103 Program 7-16 Contents of sale2.h #ifndef SALE2_H #define SALE2_H // Sale class declaration class Sale { private: float taxRate; float total; public: Sale(float rate = 0.05) { taxRate = rate; } void calcSale(float cost) { total = cost + (cost * taxRate) }; float getTotal() { return total; } }; #endif

104 Starting Out with C++ 2nd Edition, by Tony Gaddis 104 Program continues Contents of main program, pr7-16.cpp #include #include "sale2.h" using namespace std; int main() { Sale Cashier1;// Use default sales tax rate Sale Cashier2(0.06); // Use 6% sales tax rate float amnt; cout.precision(2); cout.set(ios::fixed | ios::showpoint); cout << "Enter the amount of the sale: "; cin >> amnt; Cashier1.calcSale(amnt); Cashier2.calcSale(amnt);

105 Starting Out with C++ 2nd Edition, by Tony Gaddis 105 Program continues cout << "With a 0.05 sales tax rate, the total\n"; cout << "of the sale is $"; cout << Cashier1.getTotal() << endl; cout << "With a 0.06 sales tax rate, the total\n"; cout << "of the sale is $"; cout << Cashier2.getTotal() << endl; return 0; }

106 Starting Out with C++ 2nd Edition, by Tony Gaddis 106 Program Output Enter the amount of the sale: 125.00 With a 0.05 sales tax rate, the total of the sale is $131.25 With a 0.06 sales tax rate, the total of the sale is $132.50

107 Starting Out with C++ 2nd Edition, by Tony Gaddis 107 7.20 Focus on Software Engineering: input Validation Objects This section shows how classes may be designed to validate user input.

108 Starting Out with C++ 2nd Edition, by Tony Gaddis 108 The toupper function Need to #include toupper accepts a single input character and converts it to upper case. toupper does nothing, if the input character is already uppercase or is not a letter. Example: letter = toupper( ‘a’ ) assigns the value ‘A’ to letter

109 Starting Out with C++ 2nd Edition, by Tony Gaddis 109 The CharRange input validation class contents of chrange.h #ifndef CHRANGE_H #define CHRANGE_H #include // for toupper class CharRange { private: char input;//user input char lower; //lowest valid character char upper; //highest valid character public: CharRange(char, char); // constructor char getChar(); }; #endif

110 Starting Out with C++ 2nd Edition, by Tony Gaddis 110 contents of chrange.cpp #include #include”chrange.h” using namespace std; CharRange::CharRange( char l, char u ) { lower = toupper(l); upper = toupper(u); } char CharRange::getChar() { for( ; ; ) //infinite loop terminated by valid input { cin.get(input); cin.ignore(); input = toupper(input);

111 Starting Out with C++ 2nd Edition, by Tony Gaddis 111 contents of chrange.cpp, continued if ( input upper ) { cout << “Enter a value from “ << lower; cout << “ to “ << upper << “.\n”; } else return input; } // end for loop } // end getChar function definition

112 Starting Out with C++ 2nd Edition, by Tony Gaddis 112 Program 7-17 // This program demonstrates the CharRange class. #include #include "CHRANGE.H" // Remember to compile & link chrange.cpp using namespace std; int main() { // Create an object to check for characters // in the range J - N. CharRange input('J', 'N'); cout << "Enter any of the characters J, K, l, M, or N.\n"; cout << "Entering N will stop this program.\n"; while (input.getChar() != 'N'); return 0; }

113 Starting Out with C++ 2nd Edition, by Tony Gaddis 113 Program Output with Example input Enter any of the characters J, K, l, M, or N Entering N will stop this program. j k q Only enter J, K, l, M, or N: n [Enter]

114 Starting Out with C++ 2nd Edition, by Tony Gaddis 114 7.21 Overloaded Constructors More than one constructor may be defined for a class.

115 Starting Out with C++ 2nd Edition, by Tony Gaddis 115 Example: Contents of sale3.h #ifndef SALE3_H #define SALE3_H class Sale { private: float taxRate, total; public: //default constructor Sale (float rate = 0.05) { taxRate = rate; } // overloaded constructor Sale ( float r, float cost) { taxRate = r; calcSale(cost); } void calcSale(float cost) { total = cost + (cost*taxRate); } float getTotal() { return total; } }; #endif

116 Starting Out with C++ 2nd Edition, by Tony Gaddis 116 Program 7-18 #include #include “sale3.h” using namespace std; int main() { //Declare Sale object with 6% sales tax calculated // on a $24.95 sale. Sale cashier(0.06, 24.95); cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << “With a 6% sales tax rate, the total\n”; cout <<“ of the $24.95 sale is $”; cout << cashier.getTotal() << endl; return 0; }

117 Starting Out with C++ 2nd Edition, by Tony Gaddis 117 Program output With a 6% sales tax rate, the total of the $24.95 sale is $26.45

118 Starting Out with C++ 2nd Edition, by Tony Gaddis 118 7.22 Only One Default Constructor and one Destructor A class may only have one default constructor and one destructor. Once you declare ANY constructor for a class, there is no longer a system defined default constructor for that class.

119 Starting Out with C++ 2nd Edition, by Tony Gaddis 119 7.24 Focus on Engineering: Object- Oriented Analysis 1.Identify the objects to be used in the program. 2.Define the objects’ attributes. 3.Define the objects’ behaviors. 4.Define the relationships between objects.

120 Starting Out with C++ 2nd Edition, by Tony Gaddis 120 Figure 7-7


Download ppt "Starting Out with C++ 2nd Edition, by Tony Gaddis 1 Chapter 7 – Classes and Structured Data."

Similar presentations


Ads by Google