Introduction to Records (structs)
Chapter 9
A struct is a data type that is a collection of a fixed number of components (called members), that are accessed by name.
The members of a
structmay be of different types.The syntax for defining a struct:
cppstruct StructName { dataType1 identifier1; dataType2 identifier2; … dataTypeN identiferN; }; //<- ends in a semicolon
A struct is a definition of a new data type, not a variable declaration. One must declare a variable of that type to use it. Remember, a data type is a set of possible values that can be stored in a variable with the matching type.
/**
* Defining a new type called "Movie" that holds metadata of a movie.
*/
struct Movie
{
string title;
int year;
string storyline;
string genre;
double rating;
int reviewCount;
bool isFavorite;
};Just like we can create an integer variable with int value;, variables of our struct types can be declared (e.g., Move favMove;).
Movie favMove; // example of declaring a variable with our movie typefavMovie after declaration. Move favMove;A struct type must be defined before it can be used. Normally, we put the structs above the main and function prototypes. This is okay because we are defining a type, not a variable.
Accessing struct Members
Syntax to access a struct member: structVariableName.memberName
The dot (.) is called the member-access operator.
To initialize the members of favMovie:
// Initialize some of the members of this Movie variable.
favMovie.title = "Toy Story 3";
favMovie.year = 2010;
favMovie.isFavorite = true;
// Display the movie's title
cout << favMovie.title << endl; // "Toy Story 3"favMovie after initializing some of its members.Assignment
The value of one
structvariable can be assigned to anotherstructvariable of the same type using an assignment statement (an aggregate operation).The following statement copies the contents of
favMovietooldFavMovie(both areMovievariables as defined above).cppoldFavMovie = favMovie;It is equivalent to:
cppoldFavMovie.title = favMovie.title; oldFavMovie.year = favMovie.year; oldFavMovie.storyline = favMovie.storyline; oldFavMovie.genre = favMovie.genre; oldFavMovie.rating = favMovie.rating; oldFavMovie.reviewCount = favMovie.reviewCount; oldFavMovie.isFavorite = favMovie.isFavorite;
The values of oldFavMovie are copied to favMovie, so any future changes to members of oldFavMovie, will NOT be reflected in favMovie.
You can also assign values to
structs using an ordered list in{}cpp// Set the values of the oldFavMovie in order (title, year, …, isFavorite). oldFavMovie = { "Moana", 2016, "Ocean leads girl on journey", "animation", 7.6, 264776, false };Design Note: This type of aggregate initialization may introduce bugs if you add new members to your
structtype.
Comparison (using Relational Operators)
Two
structvariables must be compared member-wise. No aggregate relational operations are given.To compare the values of
movie1andmovie2:cppif (movie1.title == movie2.title && movie2.year == movie2.year && …)
Input and Output
No aggregate input/output operations on a
structvariableData in a
structvariable must be read or written one member at a timeExample: output
favMoviecontentscppcout << "Title: " << favMovie.title << '\n' // Toy Story 3 << "Year: " << favMovie.year << '\n' // 2010 << "Storyline: " << favMovie.storyline << '\n' << "Genre: " << favMovie.genre << '\n' << "Rating: " << favMovie.rating << '\n' << "Review Count: " << favMovie.reviewCount << '\n' << "Favorite: $" << (favMovie.isFavorite ? "yes" : "no") << endl; // yes
Structs as Function Parameters and Return Values
Try the following code from the video.
/*
* Introduction to records. Creating our own structured data types!
* by Dr. Hayes
*/
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
/**
* A data type representing a student's info.
*/
struct Student
{
string firstName;
string lastName;
double gpa;
};
/**
* Display the information about the student.
*/
void print(const Student& stud);
/**
* Get a student's info from the user.
*/
void getStudent(Student& stud);
/**
* Get a student's info from the user.
*/
Student getStudent();
int main()
{
Student stud1 = {"James", "Kirk", 3.5};
Student stud2;
stud1 = getStudent();
getStudent(stud2);
if (stud1.firstName == stud2.firstName
&& stud1.lastName == stud2.lastName
&& stud1.gpa == stud2.gpa)
{
cout << "The two students are the same." << endl;
}
cout << setprecision(1) << fixed;
print(stud1);
print(stud2);
return 0;
}
void print(const Student& stud)
{
cout << stud.firstName << " " << stud.lastName
<< " has a GPA of " << stud.gpa << endl;
}
void getStudent(Student& stud)
{
cout << "Enter your first name: ";
cin >> stud.firstName;
cout << "Enter your last name: ";
cin >> stud.lastName;
cout << "Enter your current GPA: ";
cin >> stud.gpa;
}
Student getStudent()
{
Student stud;
getStudent(stud);
return stud;
}Arrays versus structs
| Aggregate Operation | Array | struct |
|---|---|---|
| Arithmetic | ||
| List Initialization | ✓ | ✓ |
| Assignment | ✓ | |
| Input / Output | *Strings only | |
| Comparison | ||
| Parameter Passing | *By Reference Only | ✓ |
| Function Returning a Value | ✓ |
Summary
struct: a collection of a fixed number of components (called members) that are accessed by name.- Components can be of different types.
structis a reserved word.- No memory is allocated for a
structtype. A memory location is reserved when a variable is declared. - The dot operator (
.) is the member-access operator- Used to access members of a
struct
- Used to access members of a
- The only built-in operations on a
structare the assignment and member access - Neither arithmetic nor relational operations are allowed on
structs - A
structcan be passed by value or reference - A function can return a value of type
struct