SlideShare a Scribd company logo
1 of 34
Copyright © 2017, 2014 Pearson Education, Inc.
Chapter 7: Introduction to Classes and
Objects
Starting Out with C++
Early Objects
Ninth Edition
by Tony Gaddis, Judy Walters,
and Godfrey Muganda
Copyright © 2017, 2014 Pearson Education, Inc.
Topics
7.12 Structures
7-2
Copyright © 2017, 2014 Pearson Education, Inc. 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 : 85 79 92 57 68 80 . . .
0 1 2 3 4 5 98 99
employee R. Jones 123 Elm 6/12/55 14.75
Copyright © 2017, 2014 Pearson Education, Inc.
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;
};
7-4
Copyright © 2017, 2014 Pearson Education, Inc.
Example struct Declaration
struct StudentStruct
{
int studentID;
string name;
short year;
double gpa;
};
7-5
structure name
structure members
Note the
required
;
Copyright © 2017, 2014 Pearson Education, Inc.
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-6
Copyright © 2017, 2014 Pearson Education, Inc.
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;
7-7
studentID
name
year
gpa
s1
Copyright © 2017, 2014 Pearson Education, Inc.
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
7-8
Copyright © 2017, 2014 Pearson Education, Inc. 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
Copyright © 2017, 2014 Pearson Education, Inc. 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 << ...;
Copyright © 2017, 2014 Pearson Education, Inc. 11
Aggregate Operations with
Structures
• struct variables must be initialized,
compared, written one member at a time.
Copyright © 2017, 2014 Pearson Education, Inc.
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;
7-12
Copyright © 2017, 2014 Pearson Education, Inc.
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
7-13
Copyright © 2017, 2014 Pearson Education, Inc.
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;
};
7-14
Copyright © 2017, 2014 Pearson Education, Inc.
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
7-15
Copyright © 2017, 2014 Pearson Education, Inc.
Initialization List Example
Structure Declaration Structure Variable
struct Dimensions
{ int length,
width,
height;
};
Dimensions box = {12,6,h};
7-16
box
length 12
width 6
height 3
Copyright © 2017, 2014 Pearson Education, Inc.
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
7-17
Copyright © 2017, 2014 Pearson Education, Inc.
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;}
};
7-18
Copyright © 2017, 2014 Pearson Education, Inc.
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;
};
7-19
Copyright © 2017, 2014 Pearson Education, Inc.
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!
7-20
Copyright © 2017, 2014 Pearson Education, Inc.
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);
7-21
Copyright © 2017, 2014 Pearson Education, Inc.
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
7-22
Copyright © 2017, 2014 Pearson Education, Inc.
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
7-23
Copyright © 2017, 2014 Pearson Education, Inc.
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;
}
7-24
Copyright © 2017, 2014 Pearson Education, Inc. 25
Contrast Arrays and structs
Copyright © 2017, 2014 Pearson Education, Inc. 26
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];
for (x = 0; x <50; x++)
cout << _______________________;
How do we
print all the
descrip fields?
parts [x].descript;
Copyright © 2017, 2014 Pearson Education, Inc. 27
structs with Arrays
• Example
const ARRAYSIZE = 1000;
struct LISTTYPE
{
int list [ARRAYSIZE]; //array containing the list
int listLength; //length of the list
}
Copyright © 2017, 2014 Pearson Education, Inc. 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; };
Copyright © 2017, 2014 Pearson Education, Inc. 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
Copyright © 2017, 2014 Pearson Education, Inc. 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
Copyright © 2017, 2014 Pearson Education, Inc. 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
Copyright © 2017, 2014 Pearson Education, Inc. 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 ( );
Copyright © 2017, 2014 Pearson Education, Inc. 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;
. . .
} ;`
Copyright © 2017, 2014 Pearson Education, Inc.
Chapter 7: Introduction to Classes and
Objects
Starting Out with C++
Early Objects
Ninth Edition
by Tony Gaddis, Judy Walters,
and Godfrey Muganda

More Related Content

Similar to Ch7Structs.pptx

Structures
StructuresStructures
Structuresselvapon
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxGebruGetachew2
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and StructuresGem WeBlog
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiMuhammed Thanveer M
 
Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++Deepak Singh
 
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...Codemotion
 
Build Your Own Angular Component Library
Build Your Own Angular Component LibraryBuild Your Own Angular Component Library
Build Your Own Angular Component LibraryCarlo Bonamico
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsITNet
 
Pitstop - One stop solution to resource management
Pitstop - One stop solution to resource managementPitstop - One stop solution to resource management
Pitstop - One stop solution to resource managementAnushree Prasanna Kumar
 
Structure in c language
Structure in c languageStructure in c language
Structure in c languagesangrampatil81
 
Introduction to Data Structures & Algorithms
Introduction to Data Structures & AlgorithmsIntroduction to Data Structures & Algorithms
Introduction to Data Structures & AlgorithmsAfaq Mansoor Khan
 
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesIntroduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesDSMS Group of Institutes
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company indiaOverview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company indiaJignesh Aakoliya
 

Similar to Ch7Structs.pptx (20)

OOP.pptx
OOP.pptxOOP.pptx
OOP.pptx
 
Structures
StructuresStructures
Structures
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
 
OOP in java
OOP in javaOOP in java
OOP in java
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++Revision notes for exam 2011 computer science with C++
Revision notes for exam 2011 computer science with C++
 
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
 
Build Your Own Angular Component Library
Build Your Own Angular Component LibraryBuild Your Own Angular Component Library
Build Your Own Angular Component Library
 
Structures
StructuresStructures
Structures
 
An Overview of Entity Framework
An Overview of Entity FrameworkAn Overview of Entity Framework
An Overview of Entity Framework
 
12Structures.pptx
12Structures.pptx12Structures.pptx
12Structures.pptx
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objects
 
Object oriented data model
Object oriented data modelObject oriented data model
Object oriented data model
 
Pitstop - One stop solution to resource management
Pitstop - One stop solution to resource managementPitstop - One stop solution to resource management
Pitstop - One stop solution to resource management
 
C Language Lecture 21
C Language Lecture 21C Language Lecture 21
C Language Lecture 21
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
 
Introduction to Data Structures & Algorithms
Introduction to Data Structures & AlgorithmsIntroduction to Data Structures & Algorithms
Introduction to Data Structures & Algorithms
 
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesIntroduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book Notes
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company indiaOverview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company india
 

Recently uploaded

Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceIES VE
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governanceWSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringWSO2
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 

Recently uploaded (20)

Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 

Ch7Structs.pptx

  • 1. Copyright © 2017, 2014 Pearson Education, Inc. Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early Objects Ninth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda
  • 2. Copyright © 2017, 2014 Pearson Education, Inc. Topics 7.12 Structures 7-2
  • 3. Copyright © 2017, 2014 Pearson Education, Inc. 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 : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99 employee R. Jones 123 Elm 6/12/55 14.75
  • 4. Copyright © 2017, 2014 Pearson Education, Inc. 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; }; 7-4
  • 5. Copyright © 2017, 2014 Pearson Education, Inc. Example struct Declaration struct StudentStruct { int studentID; string name; short year; double gpa; }; 7-5 structure name structure members Note the required ;
  • 6. Copyright © 2017, 2014 Pearson Education, Inc. 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-6
  • 7. Copyright © 2017, 2014 Pearson Education, Inc. 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; 7-7 studentID name year gpa s1
  • 8. Copyright © 2017, 2014 Pearson Education, Inc. 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 7-8
  • 9. Copyright © 2017, 2014 Pearson Education, Inc. 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. Copyright © 2017, 2014 Pearson Education, Inc. 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. Copyright © 2017, 2014 Pearson Education, Inc. 11 Aggregate Operations with Structures • struct variables must be initialized, compared, written one member at a time.
  • 12. Copyright © 2017, 2014 Pearson Education, Inc. 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; 7-12
  • 13. Copyright © 2017, 2014 Pearson Education, Inc. 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 7-13
  • 14. Copyright © 2017, 2014 Pearson Education, Inc. 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; }; 7-14
  • 15. Copyright © 2017, 2014 Pearson Education, Inc. 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 7-15
  • 16. Copyright © 2017, 2014 Pearson Education, Inc. Initialization List Example Structure Declaration Structure Variable struct Dimensions { int length, width, height; }; Dimensions box = {12,6,h}; 7-16 box length 12 width 6 height 3
  • 17. Copyright © 2017, 2014 Pearson Education, Inc. 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 7-17
  • 18. Copyright © 2017, 2014 Pearson Education, Inc. 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;} }; 7-18
  • 19. Copyright © 2017, 2014 Pearson Education, Inc. 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; }; 7-19
  • 20. Copyright © 2017, 2014 Pearson Education, Inc. 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! 7-20
  • 21. Copyright © 2017, 2014 Pearson Education, Inc. 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); 7-21
  • 22. Copyright © 2017, 2014 Pearson Education, Inc. 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 7-22
  • 23. Copyright © 2017, 2014 Pearson Education, Inc. 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 7-23
  • 24. Copyright © 2017, 2014 Pearson Education, Inc. 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; } 7-24
  • 25. Copyright © 2017, 2014 Pearson Education, Inc. 25 Contrast Arrays and structs
  • 26. Copyright © 2017, 2014 Pearson Education, Inc. 26 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]; for (x = 0; x <50; x++) cout << _______________________; How do we print all the descrip fields? parts [x].descript;
  • 27. Copyright © 2017, 2014 Pearson Education, Inc. 27 structs with Arrays • Example const ARRAYSIZE = 1000; struct LISTTYPE { int list [ARRAYSIZE]; //array containing the list int listLength; //length of the list }
  • 28. Copyright © 2017, 2014 Pearson Education, Inc. 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. Copyright © 2017, 2014 Pearson Education, Inc. 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. Copyright © 2017, 2014 Pearson Education, Inc. 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. Copyright © 2017, 2014 Pearson Education, Inc. 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. Copyright © 2017, 2014 Pearson Education, Inc. 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. Copyright © 2017, 2014 Pearson Education, Inc. 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. Copyright © 2017, 2014 Pearson Education, Inc. Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early Objects Ninth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda