In C++ structures (also known as structs) are a powerful user-defined type that lets you organize and group several related variables together into one convenient place under one name.
Each of the variables in a structure is known as a member of that structure.
Unlike an array, a structure can contain many different data types: int
, string
, bool
, etc.
struct
members are public unless specified otherwise.To create a structure, use the struct
keyword and declare each of its members inside the structures curly braces.
After the declaration, specify the name of the structure variable (i.e. myStudent in the example below):
struct { // Structure declaration
int id; // Member (int variable)
string name; // Member (string variable)
double gpa; // Member (double variable)
} myStudent; // Structure variable
The following is another example of how to create a struct, which has a constructor and a method:
// Creating the struct
struct Enemy {
std::string type;
int health;
// Constructor
Enemy(std::string t, int h) : type(t), health(h) {}
// Method
void takeDamage(int amount) {
health -= amount;
if (health < 0) health = 0;
}
void displayStatus() {
std::cout << type << " | Health: " << health << std::endl ;
}
}
//create an enemy character instance using the structs constructor
Enemy myEnemy("Spider" , 40);
// display the status
myEnemy.displayStatus();
// have the enemy take some amount of damage
myEnemy.takeDamage(7 );
// display the updated status
myEnemy.displayStatus();
Use the dot syntax (.
) to access the members of a struct.
The following example assigns data values to the members of a structure and then prints it:
// Create a structure variable called myStudent
struct {
int id;
string name;
double gpa;
} myStudent;
// Assign values to the members of myStudent
myStudent.id = 100123;
myStudent.name = "Tim";
myStudent.gpa = 3.9;
// Print the members values
cout << myStudent.id << "\n" ;
cout << myStudent.name << "\n" ;
cout << myStudent.gpa << "\n" ;
Use the comma (,
) to create multiple variables of the same one structure:
// Create multiple structure variables of this same struct
struct {
int id;
string name;
double gpa;
} student1, student2, student3;
// assign values to their members
student1.id = 100123 ;
student1.name = "Tim" ;
student1.gpa = 3.9 ;
student2.id = 100124 ;
student2.name = "Julie" ;
student2.gpa = 4.0 ;
student3.id = 100125 ;
student3.name = "Tony" ;
student3.gpa = 2.75 ;
// Print the members values
cout << student1.id << " " << student1.name << " " << student1.gpa << "\n";
cout << student2.id << " " << student2.name << " " << student2.gpa << "\n";
cout << student3.id << " " << student3.name << " " << student3.gpa << "\n";
Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.
About | Contact Us | Privacy | Terms & Conditions | © 2025 - T&J Divisions, LLC, All Rights Reserved |