C++ Structures

C++ Structures

Structures in C++ aren’t just limited to holding plain data, they have constructors, member functions, access specifiers, and even overloadable operators. When do you use a struct instead of a class?  This article explains what exactly a struct in C++ is, how it differs from classes, and why it still holds a powerful position in modern C++ programming.

Table of Contents:

What is the Structure in C++?

The structures help in grouping the different variables of different data types under a single name. It is helpful in the modeling of real-world entities. Structures are defined using the keyword struct to facilitate the creation of a complex data type. Each variable in a structure is called a member, and these members can be of different types, which can be int, float, char, etc. Organization and data manipulation become more meaningful logically in any program’s records or collection of relevant information. Unlike classes, structure members have public access by default. Structures can also contain member functions in C++.

Syntax: 

struct StructureName {
dataType member1;
dataType member2;

Here, the StructName refers to the name of the structure, member1 and member2 are the data members of the structure. Although each member has its own data type, and are essential for storing the related values within the structure. 

Working of Struct in C++

A structure in C++ can contain various types of variables under one name, so they can be made a single unit. It is declared by using the struct keyword and logically organizes related variables of potentially different data types. Each variable in a structure will be a member and will be accessed using the dot operator with structures.

Create a Structure

To utilize a structure, one needs to declare a variable of that structure type. This enables a user to store and access values for each member defined in the structure. Structure members can be accessed using a dot (.) operator. Structures can also be initialized at the time of declaration just for the sake of convenience.

Example:

struct Car {
string brand;
int year;
};
Car myCar;

Types of Structures in C++

Below are some of the most common structure types in C++:

1. Basic Structure

The fundamental structure contains only data members for grouping relevant variables, that is, by using the struct keyword, which suits very well for very basic data modeling. The members of a structure are accessed using the dot(.) operator.

Example: 

Cpp

Output: 

1. Basic Structure

This program is for Point structure-defining one Point with integers for members x and y,  then the variable p1 of that type is created. It assigns values to p1. x and p1. y and prints them using cout.

2. Nested Structure

A nested structure contains other structures as a member. The logical grouping of related entities-for example, a student with a date of birth. Using the dot operators repeatedly allows the accessing of the nested members.

Example: 

Cpp

Output: 

2. Nested Structure

The program shows a nesting structure wherein the structure Student contains as a member another structure Date, which stores the date of birth. Here, a variable s1 of type Student is created, values are assigned to the id and dob fields, and then the detail is printed using cout.

3. Array of Structures

It is an array of structures where multiple structure variables are stored in a single array, allowing you to use that array for lists, such as an executive list, a student list, a product list, etc. Each element in the array represents a separate structure. Individual elements can be accessed using an index followed by the dot(.) operator to access their members.

Example: 

Cpp

Output: 

3. Array of Structures

This program uses an array of structures to store data for multiple employees. Each Employee has an ID and salary, and two such employee records are being stored in the emp array. A for loop is used to access the particulars of each employee and print them using their index from the array.

4. Member Functions in C++ Structures

C++ structures can store functions along with data, just like class methods. These methods may even be used to encapsulate data behavior in struct types. The showLength() method inside the structure Box displays the length member’s value.

Example:

Cpp

Output: 

4. Member Functions in C++ Structures

This instance demonstrates that C++ structures may include member functions, being there through equivalent to classes. A function defined within the structure serves the purpose of displaying the value of a member variable. It proceeds to elaborate on how to define a function within a structure and how to call that function with an object of the structure. 

Get 100% Hike!

Master Most in Demand Skills Now!

5. Structure with Multiple Variables

In such cases, this structure definition may declare multiple variables. This especially applies to the case of points, students, and all other multiple similar entities.

In this example, p1 and p2 are two variables, each of a different coordinate.

Example: 

Cpp

Output: 

5. Structure with Multiple Variables

This example creates multiple variables based on the same structure, each representing varying data. It demonstrates the initiation and access to multiple objects from the same structure type. This scenario proves to be useful in modeling multiple entities like points, students, or items.

6. Named Structures

Structures can be defined by giving them a name and used later in the code to declare multiple instances. This improves the reusability as well as the readability of the code.

In this example, the structure Employee is defined to be used to declare the two variables, e1 and e2.

Example: 

Cpp

Output: 

6. Named Structures

The example specifies a structure and declares two variables of that structure. It packs together information such as name and ID into one unit and reuses the structure. This makes it easy to read, and the logical grouping of information thus makes it easier to handle structured data.

7. Local vs Global Structures

Structures can be defined globally (outside main()) or locally (inside a function). Where all programs can access the global structures, local structures are scoped. Such scoping also supports encapsulation and improves code reusability.

Example: 

Cpp

Output: 

7. Local vs. Global Structures

The example shows an important difference between global structures and local structures in C++. A global structure may be accessed throughout the entire program, while a local one may only be accessed within a particular block. This is useful in scoping and visibility of structured data for different parts of the program.

8. Typedef with Structures

With typedef, we declare better-organized and shorter names of structures when we make declarations. Instead of writing struct Time, you can just use Time as a type name.

Example: 

Cpp

Output: 

8. Typedef with Structures

With the help of typedef, this example creates an alias for structures; this improves the declarations’ cleanliness. The alias can then be directly utilized in declaring variables without writing the struct every time. This will enhance the clarity of the code and will optimize its usage in lengthy programs.

Real-Life Applications of Structures in C++

Structures provide the best definitions of real-world entities by grouping all the related data under one name. For example, a student’s structure can contain all the information, such as roll number, name, and marks. It makes management of data easy, logical, and according to efficient. Beginners can get a real idea of the practical uses of structure when organizing information in student databases or using it for inventory systems, or even employee records.

Example: 

Cpp

Output: 

Real-Life Applications of Structures in C++

This structure groups related properties of a student into one unit. In this way, it provides a means of handling its data in a logical order, which is much cleaner than handling several variables for each attribute separately.

Difference Between Structures and Classes in C++ 

Feature Structure (struct) Class (class)
Default Access Specifier Public Private
Inheritance Public by default Private by default
Member Functions Supported Supported
Encapsulation Limited (due to public default) Strong (due to private default)
Use Case Used for simple data grouping Used for complex objects and OOP concepts
Syntax Example struct Student { int id; }; class Student { int id; };
Object-Oriented Features Supported (since C++ supports both) Fully supports OOP features
Memory Layout Similar for both (implementation-dependent) Similar for both (implementation-dependent)
Constructor/Destructor Can be defined Can be defined
Best Suited For Lightweight data containers Complete OOP modeling

Arrays of Structures in C++

Arrays of structures are the perfect solution whenever you want to store many instances of the same kind (e.g., a list of books or employees).

Example: 

Cpp

Output:

Arrays of Structures in C++

The system maintains a number of employee records consisting of structures and arrays. It accepts input for an ID and a name for each of the employees and shows the names. Typically, this shows how to manage multiple records using structures and arrays.

Conclusion

C++ structure helps us classify different types of data under a single unit, thus giving a more meaningful and organized representation of that data. They are ideal for modeling real-world entities and can be provided with member functions to add some behavior to them. Structures are almost like classes, and they differ only in the default access specifiers, but are ideal for very lightweight data grouping tasks.

C++ Structures –  FAQs

Q1. What is a structure in C++?

A structure, in simple terms, is a user-defined data type in C++ that groups together variables of different data types under a single name.

Q2. How do you access members of a structure in C++?

The members or variables of a structure can be accessed using the dot (.) operator if using a structure variable, or the arrow (->) operator if using a pointer to a structure.

Q3. Can structures in C++ contain functions?

Yes, structures of C++ can have member functions with data members.

Q4. What is the difference between structures and classes in C++?

Structures, by default, have public member, whereas classes are considered to have their members private.

Q5. Can we have an array of structures in C++?

Yes, one can use an array of structures to store multiple instances of a particular structure type in C++.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner