Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 7: Introduction to Classes and Objects

Similar presentations


Presentation on theme: "Chapter 7: Introduction to Classes and Objects"— Presentation transcript:

1 Chapter 7: Introduction to Classes and Objects
Starting Out with C++ Early Objects Ninth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

2 Topics 7.12 Structures

3 Structures Recall that elements of arrays must all be of the same type
In some situations, we wish to group elements of different types scores : employee R. Jones Elm /12/

4 7.12 Structures Structure: A programmer-defined data type that allows multiple variables to be grouped together Structure declaration format: struct structure name { type1 field1; type2 field2; typen fieldn; };

5 Example struct Declaration
struct StudentStruct { int studentID; string name; short year; double gpa; }; structure name structure members Note the required ;

6 struct Declaration Notes
struct names commonly begin with an uppercase letter, because they are a type Multiple fields of same type can be declared in a comma-separated list string name,address; Fields in a structure are all public by default

7 Defining Structure Variables
A struct declaration does not allocate memory or create variables, because they are a type To define variables, use structure tag as the type name StudentStruct s1; studentID name year gpa s1

8 Accessing Structure Members
Use the name of the struct variable the name of the member separated by a dot . getline(cin, s1.name); cin >> s1.studentID; s1.gpa = 3.75; The dot is called the member selector see pr7-13.cpp

9 Aggregate Operations with Structures
Recall that arrays had no whole array operations (except passing reference to parameter) Structures DO have aggregate operators assignment statement = parameter (value or reference) return a structure as a function type

10 Aggregate Operations with Structures
Limitations on aggregate operations no I/O no arithmetic operations no comparisons cout << old_part; cin >> new_part; old_part = new_part + old_part; if (old_part < new_part) cout << ...;

11 Aggregate Operations with Structures
struct variables must be initialized, compared, written one member at a time.

12 Displaying struct Members
To display the contents of a struct variable, you must display each field or member 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;

13 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

14 Initializing a Structure
Structure members cannot be initialized 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; };

15 Initializing a Structure (continued)
Structure members are initialized at the time a structure variable is created You can initialize a structure variable’s members with either an initialization list a constructor

16 Initialization List Example
Structure Declaration Structure Variable struct Dimensions { int length, width, height; }; Dimensions box = {12,6,h}; box length 12 width 6 height 3

17 Using a Constructor to Initialize Structure Members
This is similar to a constructor for a class: the name is the same as the name of the struct it has no return type it is used to initialize data members It is normally written inside the struct declaration

18 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;} };

19 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;

20 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"; Reference the nested structure’s fields by the member variable name, not by the structure name s5.PersonInfo.name = "Joanne"; //no! See pr7-14.cpp

21 Structures as Function Arguments
You may pass members of struct variables to functions computeGPA(s1.gpa); You may pass entire struct variables to functions by value or by reference void CopyPart (PartStruct partOrig, PartStruct & partNew); See pr7-15.cpp

22 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 execution, but it 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 StudentStruct &s) // header

23 Returning a Structure from a Function
A function can return a struct StudentStruct getStuData(); // prototype s1 = getStuData(); // call The function must define a local structure variable for internal use to use with return statement

24 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; } See pr7-15B.cpp

25 Contrast Arrays and structs

26 typedef PartStruct PartsArray [50];
Arrays of structs First declare a struct (such as PartStruct) Then specify an array of that type Access elements of the array, elements of the struct typedef PartStruct PartsArray [50]; How do we print all the descrip fields? for (x = 0; x <50; x++) cout << _______________________; parts [x].descript;

27 structs with Arrays Example const ARRAYSIZE = 1000; struct LISTTYPE {
int list [ARRAYSIZE]; //array containing the list int listLength; //length of the list }

28 Hierarchical structures
Defn => structs where at least one of the components is, itself, a struct Example: struct InventoryStruct { PartStruct part; int qty_sold, re_order_qty; VendorStruct vendor; };

29 Choosing Data Structures
Strive to group logical elements of a structure together calls for hierarchical structures Push details of entities down to lower levels of the structure Data Abstraction <=> separation of logical peoperties of a data type from its implementation

30 Testing and Debugging Hints
Declaration of a struct type must end with a semicolon ; Be sure to specify the full member selector when referencing a component of a struct variable don’t leave out the struct name

31 Testing and Debugging When using an array in a struct, the index goes at the end studentRecord.scores[x] When using an array of struct, the index goes after the struct name parts[x].qty

32 Testing and Debugging Process struct members separately … the only aggregate operations will be Assignment = Parameter passing void do_it (PartStruct part); Function return PartStruct ProcessThings ( );

33 Testing and Debugging Be careful using same member names in different struct types Compiler keeps them separate OK Human readers can easily confuse them struct PartStruct { int qty; } ; struct ScoresStruct { int qty; } ;`

34 Chapter 7: Introduction to Classes and Objects
Starting Out with C++ Early Objects Ninth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda


Download ppt "Chapter 7: Introduction to Classes and Objects"

Similar presentations


Ads by Google