Accessing Structure Members in C++

Written by

Vaaruni Agarwal

Now, we know a little bit about the structures in C++, so we are going to take a look that how can we actually access the individual members of a structure in C++.

Let us continue with our previous example of books, the structure we created is:

struct Books{
    char title[50];
    int no_of_pages;
    int no_of_copies;
    char author[50];
    char category[100];
    int book_id;
} book;

Suppose, here we want to enter some data about a book, then, in that case, we have to store our information using individual members of the structure. Now, for that purpose, we have to access them.

The syntax for accessing structure member variables is as follows:

Structure_variable_name.Structure_Member = Value;

Here, structure_variable_name, is the name of the variable which is of the structure type. In our example it is book. The Structure_Member, is the member of the structure we need to access. Between them is a dot, known as the member access operator_._ 

As the name suggests, the member access operator helps us to access the members of the given structure in C++.

Let us take a look at an example:

Code

#include <iostream>
#include <cstring>

struct Books
{
    char title[50];
    char author[50];
    char subject[100];
    int book_id;
};

int main()
{
    Books Book1;          // Declare Book1 of type Book
    Books Book2;          // Declare Book2 of type Book

    // book 1 specification
    strcpy(Book1.title, "C Programming");
    strcpy(Book1.author, "Dennis Ritchie");
    strcpy(Book1.subject, "C Programming");
    Book1.book_id = 6495407;

    // book 2 specification
    strcpy(Book2.title, "C++ Programming");
    strcpy(Book2.author, "Bjarne Stroustrope");
    strcpy(Book2.subject, "C++ Programming");
    Book2.book_id = 6495700;

    // Print Book1 info
    cout << "Book 1 title: " << Book1.title << endl;
    cout << "Book 1 author: " << Book1.author << endl;
    cout << "Book 1 subject: " << Book1.subject << endl;
    cout << "Book 1 id: " << Book1.book_id << endl;

    // Print Book2 info
    cout << "Book 2 title: " << Book2.title << endl;
    cout << "Book 2 author: " << Book2.author << endl;
    cout << "Book 2 subject: " << Book2.subject << endl;
    cout << "Book 2 id: " << Book2.book_id << endl;

    return 0;
}

Output

Book 1 title: C Programming
Book 1 author: Dennis Ritchie
Book 1 subject: C Programming
Book 1 id: 6495407
Book 2 title: C++ Programming
Book 2 author: Bjarne Stroustrope
Book 2 subject: C++ Programming
Book 2 id: 6495700

Accessing Structure Members in C++