View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Struct in C++

Updated on 30/01/2025462 Views

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.

What is C++ Struct?

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.

Difference Between C++ Struct and Classes

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.

  1. Member functions: Structs do not have member functions by default. They solely focus on holding data. Classes, on the other hand, can have member functions that define operations you can perform on the data stored within the class.
  1. Default access: Struct members are public by default, meaning they can be accessed directly from anywhere in your program. Classes, by default, have private members, which can only be accessed through member functions within the class itself. This provides more control over data access within classes.

By default, C++ struct members are public. You can control member access by specifying private or protected within the declaration if needed.

How to Declare and Define C++ Struct with Examples

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.

Declaration

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.

C++ Define Struct

While declaration establishes the struct's existence, definition allocates memory for its variables. You can define a struct in two ways.

  1. Inside the declaration: This is common for simple structs.

Example:

truct Point {
int x;
double y;
};

In the above, Point is a struct with two members: x (integer) and y (double).

  1. Outside the declaration (separate block): This can be used for more complex structs or those referenced across multiple files.

Example:

// Declaration
struct Student;
// Definition in another file or block
struct Student {
std::string name;
int age;
};

Structure Tags

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.

How to Access and Initialize C++ Struct Members

Once we have declared and defined our structs, we can create instances (objects) of them and access their member variables. Here's how

Accessing Members

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;

Initializing Members

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.

C++ Struct Example Program

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.

How to Use C++ Struct Pointers

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:

Declaration and Initialization

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

Accessing C++ Struct Members through a Pointer

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 C++ Structs

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:

Declaration and Initialization

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

Initialization

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}
};

Accessing Elements and Member Variables

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.

Benefits of Arrays of Structs

Here are three main benefits of arrays of C++ struct:

  1. Efficient way to store related data for multiple objects.
  2. Simplified access to each object's information using indexing.
  3. Reusable code for operations on multiple objects within the array.

Passing C++ Struct to Functions

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.

Passing by Value (Copy)

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:

  • Safer: Changes within the function are isolated and don't affect the original struct.
  • Simpler: The function operates on a separate copy, making reasoning about side effects easier.

Disadvantages:

  • Performance overhead: Copying a large struct can be inefficient, especially for frequent function calls.
  • Unexpected behavior: If you intend to modify the original struct, passing by value won't achieve that.

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
}

Passing by Reference

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:

  • Efficiency: No copying involved, making it faster for large structs.
  • Modification: Allows the function to directly change the original struct.

Disadvantages:

  • Potential side effects: Changes within the function alter the original struct, which might lead to unintended consequences if not handled carefully.
  • Complexity: Requires understanding of pointers and references, which can be less intuitive for beginners.

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
}

C++ Struct in Class

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
};

Wrapping Up

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.

Frequently Asked Questions

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.

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

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.