Introducing struct in C++ (Structuring the Data)
Learn how to use structures (struct) in C++ to group similar data into a single user-defined data type for improved code organization and readability.
We'll cover the following
Introduction to structures (struct
) in C++
Previously, we learned procedural/structured programming, where we only worked with primitive data types like integers. In our case study, we faced an issue of passing an excessive number of variables to the function to compute arithmetic operations on mixed fractions. struct
in C++ allows us to introduce a better approach and reduce complexity while writing procedural and structured programs.
Definition of structures
To understand structures, we first need to refresh our knowledge of variables. We define a variable as a unit that stores information on a single data type ( int
, string
, and so on). Imagine having a bunch of variables of different data types grouped together under a single roof. That roof, or a user-defined data type, is a structure whose variables are called members. The slides below illustrate this concept.
Grouping different types of variables under a meaningful category/name allows users to write manageable code. Imagine writing a code to store a person’s name, age, and salary. Normally, we would need to initiate three separate variables for that. However, with the help of structures, we can make a single structure that can store all of these values under a new data type defined by the user. In the above slides, Person
is the data type defined by the user.
The syntax for declaring a structure in C++
In C++ programming, we can declare a structure using the keyword struct
followed by the structure name. Within the structure, we add the set of variables or members that we need the structure to represent. A general syntax example is shown below:
struct StructureName{dataType member1;dataType member2;...};
Here, StructureName
is the new data type or structure that we created. Let’s implement the Person
structure that we saw in the slides and see what it would look like in code format.
struct Person{string name;int age;double salary;};
Here, Person
is the structure and name
, age
, and salary
are its members.
Now, we theoretically know what a structure is, but how do we practically use structures in coding, and how do we access and initialize their members?
Declaring and initializing a structure variable
A structure is nothing but a new data type that is user-defined. Therefore, we must declare a variable of this data type to initialize its members and access them. This variable is called a structure variable.
The syntax for declaring a structure variable
To declare a structure variable, we follow the same convention we use for declaring a variable: the data type followed by the variable name. Since the data type of the structure is its user-given name, we’ll use that.
StructureName variableName;
If we take our example of the Person
structure, the declaration will look like this:
Person p;
Here, Person
is the structure name, and p
is its structure variable.
Accessing structure members
One thing that makes the structure a very powerful tool is the ability to access and modify its members. We can do that by using the .
(dot) operator, the same way we did in separate initialization. We can say that separate initialization is an example of accessing structure members.
cout << "Name: " << p.name << endl; // Accessing structure memberscout << "Age: " << p.age << endl;cout << "Salary: " << p.salary << endl;
Initializing the structure variables
Structure variables can be initialized at the time of declaration or later using assignment statements. There are two methods that we can use to initialize them.
1. Direct initialization
Direct initialization is done via the curly bracket ({}
) notation, which contains the initialized values. Here’s the general format:
StructureName variableName = {value1, value2, ...};
Here's an example of a Person
structure:
Person p = {"John", 23, 3500};
Notice how the name (John
) is initialized first, age (23
) second, and salary (3500
) last. Initializing the members follows the same order they were declared.
2. Separate initialization
Separate initialization means assigning values to the structure variable members after the structure variable is declared. We initialize every member individually using the .
(dot) operator. The general format is given below:
StructureName variableName;variableName.member1 = value1;variableName.member2 = value2;...
Here's an example of a Person
structure:
Person p;p.name = "John";p.age = 23;p.salary = 3500;
Let’s run some examples to review each concept we’ve learned.
#include <iostream>using namespace std;struct Point_3D{int x;int y;int z;};int main() {Point_3D p = {10, 20, 30}; // direct initializationcout << "X: " << p.x << endl;cout << "Y: " << p.y << endl;cout << "Z: " << p.z << endl;return 0;}
In the Direct_Initialization.cpp
file:
Lines 4–9: We declare a
Point_3D
structure with three integer variables,x
,y
, andz
, representing the coordinates of a point in a 3D plane.Line 12: We declare and directly initialize a
p
structure variable withPoint_3D
as its data type.Lines 13–15: We access individual members of the structure variable using the
.
(dot) operator and print them on the console (p.x
represents thex
coordinate of the variablep
).
In the Separate_Initialization.cpp
file:
Lines 4–9: We declare a structure named
Student
that has three variables,name
,age
, andmarks
, representing the names, ages, and grades of the students in the classroom.Line 13: We declare a
p
structure variable of theStudent
data type.Line 14: We initialize the structure variable’s members using separate initialization.
Lines 15–17: We access individual members of the structure variable using the
.
(dot) operator and print them on the console.
Example: The Patient
data type as an abstraction
Imagine we want to make a track record of hospital patients. For that, we need to record their names, ages, blood types, diseases, admission dates, and discharge dates. That’s a total of six variables that we need to make for each patient, and there are hundreds of patients in a hospital. How many variables do you think we need to make to cater to each patient, and most important of it all, what will be the naming convention (firstname1
, firstname2
, and so on)? Do you see how much of a hassle it would be for the user to maintain track of so many variables? We can avoid that by introducing a structure named Patient
and adding these six variables as its members. Here’s how it can be implemented:
#include <iostream>using namespace std;struct Patient{string name;int age;string blood_group;string disease;string admission_date;string discharge_date;};int main(){//patient 1Patient p1 = {"John", 23, "B+", "alzheimer", "1/04/2023", "11/04/2023" };//patient 2Patient p2 = {"Sara", 25, "A-", "Flu", "3/04/2023", "4/04/2023" };...return 0;}
We can reuse the Patient
structure for multiple patients, making it easy to create several instances of the same abstraction that the Patient
data type represents. This is the power of struct
in C++.
Let’s move on to the next lesson, in which we’ll discuss how we can use structures in different contexts, like making arrays of structs, passing them to functions, and making their references and pointers.