A tutorial for beginners, offerring a look into C++ structures. How structures can be defined, created, accessed and what is their actual use. Includes example code.
Download this project
There are cases in which variables or arrays are not the best solution for storing data. Say we want to store information about the leaders of a community. For the sake of simplicity, let’s suppose we only need their first name, last name and age. We can store all these in 3 variables, however since currently there are 4 leaders in this community we would need to define a total of 12 variables. There has to be a better way. Arrays, perhaps? Arrays can act as a container for multiple variables, so we can create 4 arrays, each with three fields. Wait, that’s no good: arrays can only store one type of data, and we want to store the age as an integer, not as a string. Of course, the point of all this is to demonstrate that the best solution is structs.
Let’s see how structures work. Below is the completed code which compiles (at least in Visual Studio 2003 as a Win32 Console Project).
#include "stdafx.h"
// We need this for the string data type
#include
// We need this for outputting text with cout
#include
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
   // Define the struct and its elements
   typedef struct
   {
      string FName;
      string SName;
      int Age;
   } MemberInfo;
   // Create a new instance of the struct
   MemberInfo MyMember;
   // Assign data to each struct member
   MyMember.FName = "Andrei";
   MyMember.SName = "Pociu";
   MyMember.Age = 19;
   // Output the data stored
   cout << MyMember.FName << " " << MyMember.SName << " is aged " << MyMember.Age << ".\n";
   return 0;
}
The output of this code, is as your probably expect:
Andrei Pociu is aged 19. |
Let’s review. First using typedef we defined a structure named MemberInfo. This structure is composed of 3 elements/variables, two of them being of type string and one of type int. Now that we have the structure defined and we want to use it, we create an instance of it called MyMember. We can now set the values of the variables of MyMember. Then, just like we assigned values to the variables inside the structure, we retrieve them and display to the console windows.
This is a simple and clean object-oriented approach. You can continue the code above and create as many instance of MemberInfo as you want, each holding different data.
There are a few more advanced things to say about structures, but I wanted to keep this on a beginner level. That’s all you need to know about structures as a C++ beginner.