Structures in C++ Programming

Written by

Vaaruni Agarwal

C++ provides us the facility to declare structures, to store data. As arrays helped us to store the homogeneous kinds of data the structures, on the other hand, helps to store different kinds of variables and thus store heterogeneous data.

Example:

Suppose you work in a bookstore and you want to automate the files containing records of books. So, in that case, you can declare a C++ structure in order to store different kinds of information about the same book such as the Name of the Book, Author of the Book, Category, Id of the Book, Number of Pages, Number of Copies, etc. With the help of the structure, you can easily define and store all this information very easily.

So, from the above example, we can say that the structure is nothing but a collection of heterogeneous data types in C++.

Declaring a structure in C++:

One can easily define a structure in C++, for this purpose the struct, keyword is used. 

Syntax:

struct [structure tag] {

   member definition;

   member definition;

   ...

   member definition;

} structure variable(s);

Above is a declaration for a structure in the C++ programming language, where member definition is nothing but the collection of different data types.

Let us understand this more clearly with the help of an example. Suppose we are creating a structure similar to our bookstore example, then it will look something like this:

Example:

struct Books {

   char  title[50];

   int no_of_pages;

  int no_of_copies;

   char  author[50];

   char  category[100];

   int   book_id;

} book;

In the above example, we have created a structure called Books. Now, this structure consists of a collection of different data types, like characters, integers, etc.

Now, the book, that is written after the structure body within the curly braces may be irking you out. But, that is actually a structure variable.

Now, we will learn more about the same in the upcoming chapters.

Read:

Structure Variable

Accessing Structure Members

More about Structures

Structures in C++ Programming