C++ structures are similar to classes, except that all members of a structure are public by default, whereas members of a class are private by default. A structure is defined in C++ using the keyword struct followed by the structure name. The body of the structure is enclosed in curly braces and the definition is terminated by a semicolon.
C++ structures can contain data members and member functions and can also be initialised when objects are created. They can therefore provide many of the same features as classes, although structures are commonly used when the main purpose is to group related data together.
#include <iostream>
#include <string>
struct Person
{
std::string name;
int age;
void display()
{
std::cout << name << ", " << age << '\n';
}
};
int main()
{
Person person{"John", 30};
person.display();
return 0;
}
Output:
John, 30
In this example, Person groups the related data members name and age. Both are public by default, and the structure also contains a member function, display(), which prints their values.