Structures comes from C and is used to group data together.
1 2 3 4 5 6
// Example of a Point struct
struct Point
{
int x;
int y;
};
You can now create objects of type Point.
1 2 3 4
Point p; // Create a Point variable named p.
p.x = 2; // Set the x coordinate to 2.
p.y = 4; // Set the y coordinate to 4.
std::cout << p.x << ' ' << p.y << std::endl; // Print the coordinates.
In C++ a struct is a class so you can do everything with a struct that you can do with a class.
The benefits are probably more obvious if you have many persons in your program.
1 2 3 4
// Defining three persons using struct
person davez;
person miinipaa;
person peter;
1 2 3 4 5 6 7
// Defining three persons without struct
string davezName;
int davezAge;
string miinipaaName;
int miinipaaAge;
string peterName;
int peterAge;
As you can see you get much more variables to keep track of.
If you want to have an array of persons you would have to have one array for each variable that a person has if you don't use struct.
1 2
// 10 persons using struct
person persons[10];
1 2 3
// 10 persons without struct
string personNames[10];
int personAges[10];
It also gets much easier if you want to pass a person to a function. Using struct you just have to pass 1 argument but if you don't use struct you would have to pass each variable separately and it would be easier to make mistakes, passing variables that belongs to different persons by mistake.
@Peter87 what is the advantage and disadvantage of creating a struct in outside and inside the class? and there diff. since struct has a public default access