SlideShare a Scribd company logo
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

OOP.pptx
OOP.pptxOOP.pptx
OOP.pptx
saifnasir3
 
Structures
StructuresStructures
Structures
selvapon
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
GebruGetachew2
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
Gem 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 Melayi
Muhammed 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 Library
Carlo Bonamico
 
Structures
StructuresStructures
An Overview of Entity Framework
An Overview of Entity FrameworkAn Overview of Entity Framework
An Overview of Entity Framework
iFour Technolab Pvt. Ltd.
 
12Structures.pptx
12Structures.pptx12Structures.pptx
12Structures.pptx
Aneeskhan326131
 
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
ITNet
 
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
Anushree Prasanna Kumar
 
C Language Lecture 21
C Language Lecture 21C Language Lecture 21
C Language Lecture 21
Shahzaib Ajmal
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
sangrampatil81
 
Introduction to Data Structures & Algorithms
Introduction to Data Structures & AlgorithmsIntroduction to Data Structures & Algorithms
Introduction to Data Structures & Algorithms
Afaq 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 Notes
DSMS 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 india
Jignesh 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

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 

Recently uploaded (20)

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 

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