capypad
0 day streak
cpp / beginner
Snippet

Structures for Data Grouping

Structures (struct) allow you to group related variables of different types into a single unit. Think of a struct as a custom data type you define yourself. Each variable within a struct is called a member. You can access members using the dot operator (.). Structs are the foundation for creating complex data types and are similar to classes, but members are public by default.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
 
struct Student {
std::string name;
int age;
double gpa;
};
 
int main() {
Student s1;
s1.name = "Anna";
s1.age = 20;
s1.gpa = 3.8;
Student s2 = {"Ben", 22, 3.5};
std::cout << s1.name << ": " << s1.gpa << std::endl;
std::cout << s2.name << ": " << s2.gpa << std::endl;
return 0;
}
Breakdown
1
struct Student { ... };
Defines a new struct type called Student with three members
2
Student s1;
Creates an instance of Student struct on the stack
3
s1.name = "Anna";
Assigns a value to the name member using dot operator
4
Student s2 = {"Ben", 22, 3.5};
Initializes struct members in declaration order using brace initialization
5
s1.gpa
Accesses the gpa member of struct s1