For working professionals
For fresh graduates
More
4. C++ Variable
10. C++ for Loop
12. C++ Lambda
13. Loop in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
33. Iterators in C++
34. Queue in C++
36. Stack in C++
37. ifstream in C++
40. Templates in C++
43. Namespace in C++
46. Recursion in C++
48. C++ Shell
49. Setw in C++
51. Atoi in C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
68. C++ Comments
72. Sorting in C++
Struct (short for structures) is essential for organizing our data in C++. C++ struct provides a way to group variables of different data types under a single, meaningful name. We can think of them as blueprints for creating custom data types tailored to our specific needs.
With the help of this guide, I will equip you with a solid understanding of C++ struct. We will first learn the step-by-step process of declaring and defining structs, allowing us to construct custom data types. Then, we'll cover how to access and manipulate the data stored within our structs.
Let’s dive in.
Structs let us create our own custom data types and group data without the added complexity of member functions. They are ideal when we simply need to organize related information without the need to manipulate the data.
We can think of using cpp struct like creating a custom container to hold all the information we need about a specific object. For instance, we could create a Book struct that stores variables like title (string), author (string), and pageCount (integer) under the umbrella of Book.
Both structs and classes allow us to group related data and they both create a new data type based on existing data types. However, there are two key differences.
By default, C++ struct members are public. You can control member access by specifying private or protected within the declaration if needed.
Structs offer a powerful way to bundle related data variables under a single name. We use the struct keyword to declare and define structs. Let us learn how to declare and define them in our C++ programs.
The declaration syntax for a struct looks like this:
struct <struct_name> {
// member_variable1_type member_variable1_name;
// member_variable2_type member_variable2_name;
// ...
};
In the above C++ struct syntax, <struct_name> represents the name we choose for our custom data type. We should make it descriptive and relevant to the data it holds.
member_variable_type is the placeholder for specifying the data type (e.g., int, string, double) for each variable we want to include within the struct. Finally, member_variable_name will be replaced by a meaningful name that reflects its purpose.
While declaration establishes the struct's existence, definition allocates memory for its variables. You can define a struct in two ways.
Example:
truct Point {
int x;
double y;
};
In the above, Point is a struct with two members: x (integer) and y (double).
Example:
// Declaration
struct Student;
// Definition in another file or block
struct Student {
std::string name;
int age;
};
Structure tags serve as unique identifiers for structs. They are optional in modern C++ but can be useful for clarity, especially when dealing with pointers to structs.
struct Point { // Declaration with structure tag
int x;
double y;
};
Point myPoint; // Creating an instance of Point
// Using the structure tag with pointers
Point* ptr = &myPoint; // ptr points to a Point object
In this example, Point is the structure tag used to clarify that ptr is a pointer to a Point struct.
Once we have declared and defined our structs, we can create instances (objects) of them and access their member variables. Here's how
The dot operator (.) is your key to accessing the member variables of a struct instance.
Syntax:
struct_name struct_instance_name.member_variable_name; |
Example:
struct Book {
std::string title;
std::string author;
int yearPublished;
};
Book myBook; // Create an instance of Book
myBook.title = "The Hitchhiker's Guide to the Galaxy";
myBook.author = "Douglas Adams";
myBook.yearPublished = 1979;
std::cout << "Book Title: " << myBook.title << std::endl;
There are two main ways to initialize struct members when creating an instance.
1. During declaration: You can directly assign values to member variables within the struct declaration:
struct Book {
std::string title = "Unknown"; // Default value for title
std::string author;
int yearPublished = 0;
};
Book myBook; // Members already initialized with default values
2. Using member initialization lists: For more control, use a member initialization list after the struct name in parentheses:
struct Book {
std::string title;
std::string author;
int yearPublished;
};
Book myBook("The Martian", "Andy Weir", 2011); // Initialize members in specific order
Member initialization lists ensure members are initialized in the order they are listed, providing more clarity and avoiding potential issues with default constructors.
Here is a linked list program in C++ using struct that you can run and try out yourselves:
Code:
#include <iostream>
// Define a struct for a node in the linked list
struct Node {
int data;
Node* next; // Pointer to the next node in the list
};
// Function prototypes
void insertAtHead(Node** head_ref, int new_data);
void printList(Node* head);
int main() {
Node* head = nullptr; // Initially, the list is empty
// Insert elements at the front of the linked list
insertAtHead(&head, 5);
insertAtHead(&head, 4);
insertAtHead(&head, 3);
insertAtHead(&head, 2);
insertAtHead(&head, 1);
std::cout << "Created Linked List: ";
printList(head);
return 0;
}
// Inserts a new node at the head of the linked list
void insertAtHead(Node** head_ref, int new_data) {
// Create a new node
Node* new_node = new Node;
new_node->data = new_data;
new_node->next = *head_ref;
// Update the head pointer
*head_ref = new_node;
}
// Prints the contents of the linked list
void printList(Node* head) {
while (head != nullptr) {
std::cout << head->data << " ";
head = head->next;
}
std::cout << std::endl;
}
The above cpp struct example defines a Node struct that holds an integer value (data) and a pointer (next) to the next node in the list. The insertAtHead function creates a new node, sets its data and next pointer, and then updates the head pointer of the list to point to the new node.
Finally, the printList function iterates through the list, printing the data of each node, until it reaches the end (null pointer). If you wish to learn how to code in C++, you can check out upGrad’s software engineering courses.
Struct pointers allow us to indirectly access and manipulate structs by storing the memory address of a struct instance. Here is how we can use them effectively:
Declare a pointer to a struct by specifying the struct name followed by an asterisk (*).
Syntax:
struct_name* pointer_name; |
Similar to regular variables, we can initialize a pointer in two ways.
Null pointer:
struct Point {
int x;
double y;
};
Point* ptr = nullptr; // Pointer points to nothing (null)
Pointing to an existing struct:
Point myPoint = {10, 20.5}; // Create a Point instance
Point* ptr = &myPoint; // ptr now points to the memory address of myPoint
The arrow operator (->) is used to access member variables of a struct through a pointer.
Syntax:
pointer_name->member_variable_name; |
Example:
ptr->x = 30; // Modify x member through the pointer
std::cout << "New x value: " << ptr->x << std::endl;
We should always ensure the pointer points to a valid struct instance before accessing members. Attempting to access members through a null pointer can lead to program crashes. Dereferencing a pointer (using *) retrieves the actual struct value at the memory location pointed to.
Example (dereferencing):
Point newPoint = *ptr; // Create a new Point object with the values from the pointed-to struct |
Arrays of structs offer a powerful way to manage collections of similarly structured data. Here's how to create and utilize them in your C++ programs:
Declare an array of structs by specifying the struct name within square brackets ([]) after the array size.
Syntax:
struct_name array_name[size]; |
Example:
struct Student {
std::string name;
int age;
};
Student students[3]; // Array to hold information for 3 students
Similar to individual structs, you can initialize arrays of structs in two ways:
Individual elements:
students[0] = {"Alice", 20};
students[1] = {"Bob", 22};
students[2] = {"Charlie", 19};
Member initialization list:
Student students[3] = {
{"Alice", 20},
{"Bob", 22},
{"Charlie", 19}
};
Use the array index and the dot operator to access the member variables of a specific struct within the array.
Syntax:
array_name[index].member_variable_name; |
Example (Iterating through the array):
for (int i = 0; i < 3; ++i) {
std::cout << "Student " << i + 1 << ": " << students[i].name << " (age: " << students[i].age << ")" << std::endl;
}
for (int i = 0; i < 3; ++i) {
This code iterates through the students array, printing the name and age of each student using their respective member variables.
Here are three main benefits of arrays of C++ struct:
Structs, like other variables, can be passed to functions in C++. However, the way you pass them determines how the function interacts with the data. Here's a breakdown of passing structs by value and by reference.
In this approach, a copy of the entire struct is created and passed to the function. Any modifications made within the function affect the copy, not the original struct.
Advantages:
Disadvantages:
Example:
struct Point {
int x;
double y;
};
void modifyPoint(Point p) { // Function receives a copy of p
p.x = p.x * 2;
p.y = p.y * 2;
}
int main() {
Point myPoint = {5, 10.5};
modifyPoint(myPoint); // Pass a copy of myPoint
std::cout << "Original Point (unchanged): x = " << myPoint.x << ", y = " << myPoint.y << std::endl;
// Output: Original Point (unchanged): x = 5, y = 10.5
}
Here, you pass the memory address of the original struct to the function using a reference variable (&). The function can then directly access and modify the original struct.
Advantages:
Disadvantages:
Example:
struct Point {
int x;
double y;
};
void modifyPoint(Point& p) { // Function receives a reference to p
p.x = p.x * 2;
p.y = p.y * 2;
}
int main() {
Point myPoint = {5, 10.5};
modifyPoint(myPoint); // Pass a reference to myPoint
std::cout << "Modified Point: x = " << myPoint.x << ", y = " << myPoint.y << std::endl;
// Output: Modified Point: x = 10, y = 21
}
In C++, structs can be included within classes as members, allowing us to create more complex data structures. For instance, imagine a Customer class. We might want to store information about the customer's address within this class. We can define a struct Address and include it as a member of the Customer class.
Example:
struct Address {
std::string street;
std::string city;
std::string state;
int zipCode;
};
class Customer {
public:
std::string name;
Address address; // Address struct as a member variable
// ... other customer information and methods
};
According to me, structs are incredibly important as they offer an effective way to group related data variables under a single name, promoting code organization and data clarity. They are essential building blocks for creating more complex data structures in C++.
If you wish to learn programming languages such as C++, you can check out upGrad’s computer science programs such as the Master’s in Computer Science Program.
What is a struct in C++?
A struct in C++ is a user-defined data type that groups variables under a single name.
How is a struct different from a class in C++?
Structs differ from classes in C++ by default: structs have no member functions and public members, while classes can have both private and public members and functions.
How do you define a struct in C++?
You define a struct in C++ with the struct keyword, followed by the struct name, curly braces containing member variables and their data types.
Can a struct have member functions in C++?
No, structs in C++ cannot have member functions.
Can you nest structs in C++?
Yes, you can nest structs within structs in C++ for complex data organization.
What are some common use cases for structs in C++?
Common use cases for structs in C++ include representing real-world entities (e.g., Point, Book), and creating custom data structures (e.g., linked lists).
Can you use inheritance with structs in C++?
No, inheritance is not supported with structs in C++.
Are structs passed by value or by reference in functions in C++?
Structs in C++ can be passed by value (copy) or by reference depending on your needs.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.