In C++, a structure (struct) is a composite data type that allows you to group together variables of different data types under a single name. It is similar to a class in C++, but unlike classes, structures do not support member functions or access control (public, private, protected). Structures are primarily used for grouping data members, and the data within a structure can be accessed directly.
struct Student {
int rollNumber;
char name[50];
int age;
float marks;
};
In this example, we've defined a structure named Student
. It contains four data members:
rollNumber
of typeint
name
of type character array (char[50]
) to store the student's nameage
of typeint
marks
of typefloat
You can then declare and initialize variables of this structure type:
Student student1; // Declare a variable of the Student structure
student1.rollNumber = 101; // Initialize its members
strcpy(student1.name, "John Doe");
student1.age = 20;
student1.marks = 85.5;
You can also define and initialize a structure variable in one line:
Student student2 = {102, "Alice Smith", 19, 92.5};
Accessing the members of a structure is straightforward:
cout << "Student 1 Roll Number: " << student1.rollNumber << endl;
cout << "Student 1 Name: " << student1.name << endl;
cout << "Student 1 Age: " << student1.age << endl;
cout << "Student 1 Marks: " << student1.marks << endl;
Structures are useful for organizing related data into a single unit. For example, you might use structures to represent complex data types like points in 3D space, dates, or records in a database. They can be passed as arguments to functions, returned from functions, and stored in arrays or other data structures.
#include
#include
using namespace std;
struct Date {
int day;
int month;
int year;
};
void printDate(const Date& date) {
cout << "Date: " << date.day << "/" << date.month << "/" << date.year << endl;
}
int main() {
Date today = {27, 10, 2023};
printDate(today);
Date birthday;
birthday.day = 15;
birthday.month = 5;
birthday.year = 1995;
printDate(birthday);
return 0;
}