cpp / beginner
Snippet
Grouping Data with Structs
Structs allow you to group related variables of different types under a single name. They are the foundation for creating custom data types. Each variable within a struct is called a 'member'. You can access members using the dot operator (.). Structs are similar to classes but default to public access in C++.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>#include <string>struct Student {std::string name;int age;float gpa;};int main() {Student student1;student1.name = "Alice";student1.age = 20;student1.gpa = 3.8f;Student student2 = {"Bob", 22, 3.5f};std::cout << student1.name << " (" << student1.age << ") - GPA: " << student1.gpa << std::endl;std::cout << student2.name << " (" << student2.age << ") - GPA: " << student2.gpa << std::endl;return 0;}
Breakdown
1
struct Student { ... };
Defines a custom data type called Student with three members
2
std::string name;
A string member to store the student's name
3
int age;
An integer member to store the student's age
4
float gpa;
A float member to store the grade point average
5
Student student1;
Creates a Student variable named student1
6
student1.name = "Alice";
Assigns values to members using the dot operator