Lesson 14 - Structures in the C++ language

In the previous lesson, Functions in the C++ language, we learned how to declare custom functions in the C++ language. In today's tutorial, we'll introduce structures. Structures are an intermediate step between the procedural and object-oriented programming styles. In C++, structures were replaced by classes, but most libraries still use structures. Therefore, we're going to use them today. Since we're only going to create a simple program, we won't use custom functions today. Just remember that if it was a bit longer, we would need to split it into separate functions.

Storing complex items

Consider that we want to store data for a single user. He/she has a name, an age, and has a street address. Using our current knowledge, we'd create multiple variables to store the data:

int main()
    string name = "John Smith";
    int age = 33;
    string street = "Skew street 5";

    return 0;

However, we usually store more than a single user, in fact, we often store large amounts of users. As we already know, we use arrays for storing multiple items of the same type. However, since users contain values of 3 different types, we'd have to create 3 different arrays. One for names, the second one for ages, and the third one for streets. Let's create several arrays that are 10 elements long (to store a maximum of 10 users). We'll demonstrate its functionality by storing 2 users and printing them to the console using a for loop.

string names[10];
int ages[10];
string streets[10];

names[0] = "John Smith";
ages[0] = 33;
streets[0] = "Skew street 5";

names[1] = "Jack Brown";
ages[1] = 28;
streets[1] = "Sunnyvale 8";

for (int i = 0; i < 2; i++)
    cout << "The user at the index " << i << endl;
    cout << "Name: " << names[i] << endl;
    cout << "Age: " << ages[i] << endl;
    cout << "Street: " << streets[i] << endl << endl;

The result:

Console application
The user at the index 0
Name: John Smith
Age: 33
Street: Skew street 5

The user at the index 1
Name: Jack Brown
Age: 28
Street: Sunnyvale 8

The program looks pretty impressive considering our skills. Once we learn to store data in files, we could program something like a phone book this way. Printing using a loop should be clear. We're simply working with indexes < 2 since we don't have any more people at the moment.


To avoid declaring so many confusing arrays, the C++ language allows us to declare structures. Structures are a data type which is represented by a single variable but contains multiple values (sometimes referred to as a record type). They may remind you of an array. However, it's items don't all have to be of the same type and they're not accessed using numbers (they're accessed via their names). The best thing we could do is to create a User structure in order to store users. Add the following definition somewhere into the global scope above the main() function:

struct User
    string name;
    int age;
    string street;

The most important thing here is the struct keyword by which we say that we're creating a new structure. We declare items for the structure within the curly brackets block as ordinary variables. Keep in mind that there has to be a semicolon after the structure declaration.

Now, let's rewrite the main() function to look like the following:

int main()
    User users[10];
    users[0].name = "John Smith";
    users[0].age = 33;
    users[0].street =  "Skew street 5";

    users[1].name = "Jack Brown";
    users[1].age = 28;
    users[1].street = "Sunnyvale 8";

    for (int i = 0; i < 2; i++)
        cout << "The user at the index " << i << endl;
        cout << "Name: " << users[i].name << endl;
        cout << "Age: " << users[i].age << endl;
        cout << "Street: " << users[i].street << endl << endl;
    return 0;

The whole application is way more readable now. It simply contains an array of the User type instead of 3 arrays as before. We use the . (dot) operator to access structure items. If we use structures dynamically (which we can't do yet), we'd use the arrow operator (->). We'll cover all of this further along in the course.

Alternative structure definitions

Sometimes, a structure is even defined directly with a variable:

struct {
    string name;
    int age;
    string street;
}  users[10];

Consider this last example as a rather deterrent code. Making it a little bit shorter doesn't always mean it's clearer. Furthermore, we can't use such structures from multiple places in our program.

Note: Of course, we're not limited to using structures in arrays. Structures are an ordinary data type just like int. However, it's not very common to use structures in the C++ language. The problem is that there are libraries which are mainly written for the C language and work in C++ as well. However, C doesn't support classes (which we'd use in C++) so you'll encounter structures when working with libraries.

Note: Aside from structures, we can declare also so-called unions in the C++ language. Unions look just like structures but variables of the union types can only have one of their items (values) initialized. It's like each user could either have a name, or age, or a street address. This doesn't make much sense with users. However, we may run into situations when we need to store items and each item is a bit different. However, unions didn't become very popular since people have issues determining which of the values is initialized. Therefore they're often wrapped in structures or classes, so we won't get into them here.

We'll get back to structures once more throughout our courses. The source code for today's application is available for download below the article.

You have now finished the introductory course into the C++ language. Congratulations, you're now aware of most of its constructs! :) Of course, we still have lots to cover. There are more exercises for you to practice. Afterward, the course continues in the Dynamic memory management in the C++ language course. There, you'll learn how to allocate memory dynamically and stop being limited by the lengths of static arrays. Since these matters are a bit complicated, the whole basics course worked around it so you could try different C++ constructs without being overwhelmed. I'm looking forward to seeing you all in the next course. There, we'll create real-world applications!



Downloaded 0x (317.38 kB)
Application includes source codes in language C++



Article has been written for you by David Capka
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Previous article
Functions in the C++ language
All articles in this section
C++ basic constructs
Activities (8)




To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!