C++ Structures
A structure is a type that groups named pieces of data together. Each piece is a member with its own name and type.
A structure with two members
The Person structure groups a name and an age. The object fills both members, and both members print.
#include <iostream>
#include <string>
struct Person {
std::string name;
int age;
};
int main() {
Person p;
p.name = "Hana";
p.age = 27;
std::cout << p.name << std::endl;
std::cout << p.age << std::endl;
return 0;
}Changing a member
The age member holds 22 at first. A new value replaces it, and the age prints again.
#include <iostream>
#include <string>
struct Person {
std::string name;
int age;
};
int main() {
Person p;
p.name = "Ana";
p.age = 22;
std::cout << p.age << std::endl;
p.age = 23;
std::cout << p.age << std::endl;
return 0;
}Two objects of one type
Both objects come from the Person structure. Each object holds its own name and age.
#include <iostream>
#include <string>
struct Person {
std::string name;
int age;
};
int main() {
Person first;
first.name = "Hana";
first.age = 27;
Person second;
second.name = "Bo";
second.age = 31;
std::cout << first.name << " " << first.age << std::endl;
std::cout << second.name << " " << second.age << std::endl;
return 0;
}Example
#include <iostream>
#include <string>
struct Book {
std::string title;
int pages;
};
int main() {
Book book;
book.title = "Sea Tales";
book.pages = 210;
std::cout << "Title: " << book.title << std::endl;
std::cout << "Pages: " << book.pages << std::endl;
return 0;
}Key points
- Use struct to define a structure and its members.
- A member is one named piece of data inside a structure.
- An object is a value made from a structure type.
- Use a dot to read or change a member of an object.
- A structure definition ends with a semicolon after its closing brace.
- Members of a structure are open by default, so any code can reach them.
In this example, the Book structure groups a title and a page count. The object fills both members. The two print lines read the members through a dot and place a label before each value.
Note
One structure type can make many objects, and each object holds its own member values.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does code read the age member of a Person object named p?