More on C++ Structures

Written by

Vaaruni Agarwal

So, far we have learned some basics that how can we access members of a structure, what is a structure, its use and how can we use a structure in C++. But, there are many more things about structures that we have still not covered. So, we will look into them in this chapter.

Importance of Structures:

But, before that, let us talk about the importance of the structures in C++. As we have already seen that structures are a collection of heterogeneous type of data, and they can be used to store different types of information. Varying data types can be accessed using a common structure type.

This helps the programmers to store the varied types of data in a single place. Usually, when we try and access different types of information that relates to a particular entity then the structures are used.

Example:

If we want to update a student database, then student is a single entity and it will be required to store some important information, like student’s name, id, address, course, fees, course id, date of birth, etc.

All these information which are of different data types can be stored in a common structure, Student.

 The typedef Keyword:

We already know, that keywords are some words which have a predefined meaning in the C++ compiler and are used for a special purpose only. The typedef keyword, is used to define an alias or another name for a structure.

Example:

typedef struct {

   char  title[50];

   char  author[50];

   char  subject[100];

   int   book_id;

} Books;

Here, we have defined an alias Books for the structure that we have created using the typedef keyword.

Now, anywhere in our program, we can easily use this alias, Books to access, the members of the structure and perform any possible operations as well.

More on C++ Structures