C++ Structs
We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of comparable data kinds at contiguous memory regions in C++.
Structures in C++, unlike Arrays, are user-defined data types that are used to hold groups of objects of dissimilar data types.
In C++, what is a Struct?
A Struct is a data structure in C++ that may be used to hold pieces of several data types together. A C++ structure is a programmer-defined data type. The structure provides a data type that may be used to aggregate objects of various data types into an individual data type.
Example:
Consider storing information about someone, such as their name, standard and roll number. To keep the data independently, you may construct variables such as name, standard, and roll_num.
Although, we would most probably be needing to keep the same data for a greater amount of people in the future. It indicates that distinct variables will be established for different people. Name1, standard1, roll_num1, and so forth. This is a compilation of all linked data under one name i.e. Info which is a struct. Hence, it is preferable to construct a struct to avoid this.
When should a Structure Be Used?
Here are a few reasons why you should use structure in C++ :
- When we want to keep elements of many data types in one data type, we use a struct.
- Structs in C++ are value types rather than reference types. If we don't plan to change our data after it's created, we use a struct.
How to initialize a struct in C++?
The keyword struct, accompanied by an identifier, is used to build a C++ structure. The identifier will become the struct's name. The syntax for creating a C++ struct is as follows:
Syntax:
struct struct_names
{
// structure data members
}
The struct keyword is used in the above syntax. The struct_names is the structure's name. Curly brackets are used to add the struct elements. These distinct individuals more often be from various different data categories.
Example:
struct Student
{
char name[40];
int standard;
int roll_num;
}
Explanation:
Student is a three-membered structure in the example above. Name, standard and roll_num are among the members. This structure is built with char data type for name, integer datatype for standard and integer datatype for roll_num also. Memory will be allocated only after a variable will be appended to the struct.
Creating instances for a struct:
We generated a struct called Student in the preceding example. We can make a struct variable like this:
Student st;
The struct variable st is of the type Student. This variable can be used to access the struct's members.
Accessing the members of a struct:
We utilise the struct instance and the dot “.” operator to access the element of the struct. The member access operator is represented by a period between the name of the structure variable and the name of the structure member we want to access. To define variables of the structure type, we'd use the term struct. To get the member standard of struct Student :
Example:
st.standard = 8;
Explanation:
We used the struct's instance st, to get the member standard of struct Student. After that, we changed the member's standard to 8.
Example:
#include <iostream>
using namespace std;
struct Student
{
int standard;
int roll_num;
};
int main(void) {
struct Student st;
st.standard = 8;
st.roll_num = 21;
cout << "Student’s standard: " << st.standard << endl;
cout << "Student’s roll number: " << st.roll_num << endl;
return 0;
}
Output:
Student’s standard: 8
Student’s roll number: 21
Explanation:
In the above example, we created a struct Student with two struct members of integer type namely standard and roll_num. Then in the main() function we created an instance st of struct Student. Using that instance, we provided values for standard and roll_num and they were printed as required.
Structure pointer:
A pointer that refers to a structure can be created. It's analogous to how pointers to native data types like as int, float, double, and so on are produced. In C++, a pointer is used to hold a memory address. Members are accessed using the arrow (->) operator rather than the dot (.) operator when we have a pointer pointing to a structure.
Example:
#include <iostream>
using namespace std;
struct Lengths
{
int mtrs;
float ctmtrs;
};
int main()
{
Lengths *ptr, z;
ptr = &z;
cout << "Enter length in meters: ";
cin >> (*ptr).mtrs;
cout << "Enter length in centimeters: ";
cin >> (*ptr).ctmtrs;
cout << "Length = " << (*ptr).mtrs << " meters " << (*ptr).ctmtrs << " centimeters";
return 0;
}
Output:
Enter length in meters: 10
Enter length in centimeters: 34
Length = 10 meters 34 centimeters
Explanation:
In the above example, we created a struct Lengths with two struct members of integer type namely mtrs and ctmtrs. Then in the main() function we created a pointer variable *ptr and a normal variable z of type Lengths whose address is stored in the pointer variable. Using that instance, we asked values for mtrs and ctmtrs and they were printed as required.
Passing Struct as function argument:
A struct can be sent as an argument to a function. This is proceeded in the same way as the passing of a standard argument. A function can also be supplied struct variables. When you do need to present the data of struct members, this is an excellent example.
Example:
#include<iostream>
using namespace std;
struct Student
{
int standard;
int roll_num;
};
void func(struct Student st);
int main()
{
struct Student st;
st.standard = 9;
st.roll_num = 24;
func(st);
return 0;
}
void func(struct Student st)
{
cout << "Student’s standard: " << st.standard << endl;
cout << "Student’s roll number: " << st.roll_num << endl;
}
Output:
Student’s standard: 9
Student’s roll number: 24
Explanation:
In the above example, we created a struct Student with two struct members of integer type namely standard and roll_num. Then created a function func() that takes the instance st of struct Student as the argument. Then in the main() function we created an instance st of struct Student. When that function func() will be called the instance of the struct st will be passed as an argument and using that instance, we provided values for standard and roll_num and they were printed as required.
Drawbacks of C++ Structure:
C++ Structures have the following drawbacks:
- Built-in data types cannot be used with the struct data type.
- On structural variables, operators like +, -, and others are not allowed.
- Data concealing is not possible with structures. Any function, regardless of its scope, can access the members of a structure.
- Static members cannot be defined within the structural body.
- Constructors cannot be built inside a struct.
Differences between a Struct and a class:
Parameters | Struct | Class |
Definition | A structure is a collection of variables of different data kinds with the same name. | A class in C++ is a single structure that contains a collection of linked variables and functions. |
Declared as | struct structures_name{ type structs_member1; type struct_member2; . type struct_memberN; }; | class class_names{ data members; members func; }; |
General | Every member is set to 'public' when no access specifier is supplied. | Every member is set to 'private' if no access specifier is given. |
Objective | Data classification. | Further inheritance and data abstraction. |
Instances | The 'structure variable' is the name for a structure instance. | The term 'object' refers to a class instance. |
Used for | It's for tiny bits of information. | It stores a large quantity of data. |
Memory Allocation | The stack is used to allocate memory. | The heap is where memory is allocated. |
Constructor and Destructor | It's possible that it only has a parameterized constructor. | It might include any number of both, constructors and destructors. |
Reusability | Not reusable | Fully reusable |
Initialization of members variables | Not allowed. | Allowed. |
Default empty size | 0 Bytes | 1 Byte |
Garbage collection | Since it employs pass by value, this isn't feasible. | Since it utilises pass by reference, it's possible. |
Memory management | Poor | Effective |
Conclusion:
- A struct is a data structure for storing data pieces of various kinds.
- A struct contains data elements of diverse kinds, while an array contains data items of the same type.
- When the data pieces are not supposed to change value, a struct must be utilised.
- The dot (.) operator is used to access the data members of a struct.
- We must first build a struct instance.
- The struct keyword is used to build a C++ struct.
- Pointers referring to structs are constructed in the same way that pointers pointing to normal types are.
- A struct could be supplied to a function as an argument in the same manner that regular functions are.