Structures In C++

Structures In C++
Structures In C++

Introduction

Suppose you are a car garage owner and you want to maintain a record of each car in your garage. You want to store the color, engine capacity, and model of each vehicle. How will you accomplish this? Note that Arrays in C + + are not going to help you, as they store data of the same type. Here, the problem is that the color will be a string and engineCapacity will be an integer. So structures in C++ come here for your rescue.

What are Structures in C++?

Structures in C++ are like containers that store variables of different data types in them. Structures in C++ are user-defined data types, i.e., this data type is not in-built in C++. Explore more about data types in C++ here. You can visualize structures in C++ like this:-

Suppose the container name is Employee, i.e., we’re having a structure named Employee. This container will store information about Employees like name, age, and salary.


Structures in C++

Now we have understood what structures in C++ are So let’s move towards defining the structures through code in C++:-

A structure is created using a keyword struct. Structures in C++ can contain:

  • Data Members:- These are normal variables in C++
  • Member Functions:- These are normal functions in C++
struct Employee
{
       string name;
       int age;
      float salary;

};

Note: Always end structure definition with a semicolon, as shown above.

Let’s move towards understanding member functions inside structures in C++, it is worth noting that structures defined in C cannot have member functions, however, structures in C++ allow having member functions along with data members.

struct Employee
{
    // Data Members
    string name;
    int age;
    float salary;

    // Member functions (Only in C++)
    void display(){
        cout << “The employee age is: ” << age;
    }

};

Now to make use of this structure, we have to make structure variables, but before that, I want to share an important concept i.e.No memory is allocated when you create a structure. Now you must be wondering why it is so? Let me clarify this here, see structures in C++ are like the blueprint for variable creation. Space will be allocated only when you create structure variables.

How to make Structure Variables?

In C++ you can define structure Variables in two ways:-

  • Define a structure variable in a separate declaration like you define primitive data type variables in C++.
struct Employee
{
       string name;
       int age;
      float salary;

};
struct Employee e1;

Note: In C++, writing struct keyword before the declaration of a variable is optional i.e., we can also write Employee e1;  instead of struct Employee e1;

  • The second way is to define a structure variable is defining them at the time of structure declaration:
struct Employee
{
       string name;
       int age;
      float salary;

}e1; //variable is declared with Employee

You can define as many structure variables as you want. Suppose you want to store information of 5 Employees, then you can make five structure variables. Now we’ve learned to define structure variables, so next, we should learn about accessing the data members inside structures using these structure variables.

How to Access Members of a Structure?

The dot operator(.) is used in C++ to access structure members i.e the data members and member functions. Suppose you want to access the age of an employee, then you can write e1.age;  

You can also assign a value using a dot operator like e1.age = 30;    

We can initialize structure variables without using the dot operator also. Let’s see programs by both ways to initialize structure variables.

//C++ program using dot operator
#include <iostream>
#include <string>
using namespace std;

//creating a structure named employee
struct Employee
{
    string name;
    int age;
    float salary;
    
    void display()
    {
        cout << "Name: " << name << endl;
        cout <<"Age: " << age << endl;
        cout << "Salary: " << salary;
    }
};

int main()
{
    //making variable of the structure defined above
    Employee e1;

    //accessing data member inside structure using structure variable
    cout << "Enter your name: ";
    cin >> e1.name;
    cout << "Enter your age: ";
    cin >> e1.age;
    cout << "Enter your salary: ";
    cin >> e1.salary;

     //accessing member function inside structure using structure variable
    e1.display();

    return 0;
}

//C++ program without using dot operator
#include <iostream>
#include <string>
using namespace std;

struct Employee
{
    string name;
    int age;
    float salary;

    void display()
    {
        cout << "Name: " << name << endl;
        cout <<"Age: " << age << endl;
        cout << "Salary: " << salary;
    }
};

int main()
{
    //Order of structure variables will be followed in initialization
    Employee e1 = { "Ninja", 15, 500000 };
    e1.display();
    return 0;
}

So, from the above two codes, you’ve mastered two ways of initializing variables in the structures in C++. One way is to initialize the variables using dot operator and the second way is without using dot operator but here, with the second method, you need to be careful with the order of values you are passing.

Values should be passed in the same order as you have defined variables in the structure otherwise you will get unexpected results. Now let’s discuss structure pointers.

Pointers To Structure 

In C++, you must have worked with pointer variables for primitive data types like int, float, and char in C++. We can also make pointers for user-defined data types like structures here. Before moving forward, if you want to know more about pointers, then have a look here.

Let’s see a program where we will make a pointer variable to a structure:

#include <iostream>
using namespace std;
struct Employee
{
       string name;
       int age;
      float salary;

};

int main(){
       Employee* e;
      return 0;
}

In this program, we created a pointer e of user-defined data type Employee. To access data members with a pointer, you have to use the arrow operator (->) instead of dot operator(.)

Let’s modify the program discussed above using pointers so that it can become crystal clear to you.

#include <iostream>
#include <string>
using namespace std;

struct Employee
{
    string name;
    int age;
    float salary;
};

int main()
{
    Employee* e1 = new Employee;
    
    cout << "Enter your name: ";
    cin >> e1->name;
    cout << "Enter your age: ";
    cin >> e1->age;
    cout << "Enter your salary: ";
    cin >> e1->salary;

    cout << "Name: " << e1->name << endl;
    cout <<"Age: " << e1->age << endl;
    cout << "Salary: " << e1->salary;

    return 0;
}

So in this program, you first created a structure pointer and then used that to access structure members.

Frequently Asked Questions

Why do we need structures in C++?

We need structures to store variables of different data types in a single container. Unlike arrays in C++, Structures in C++ can store int value, float value, or whatever data type you want to keep.

How are structures in C++ different from classes in C++?

The significant difference between classes and structures in C++ is from a security perspective. By default, class members have private access specifiers, but structure members have public access specifiers by default. Another difference is that the class needs to have a constructor and a destructor, whereas there is no such need for structures in C++.

Why do I need an arrow operator(->) with structure pointers instead of a dot(.) operator?

Pointers store the address of a structure variable, so before accessing the structure members, we first need to dereference the operator; that’s why we need to use the arrow operator instead of the dot operator.Remember (ptr->a) is same as ((*ptr).a).

When I define a structure does any memory get allocated to it in my program?

No! Always remember structure is like a blueprint for the structure variables. Memory will only be allocated when you will be defining variables of the structure.

Can I have an array of structures?

Yes! You can. The structure is just another user-defined data type and we can do the same things with structs as we do with primitive data types.

Key Takeaways

In this blog, you learned that we need structures to store values of different data types under a single name. You have two options to declare a structure variable either at the time of structure definition or in a separate line like we define all other primitive data types.

You can also specify a pointer to a structure but be careful with it as in this case; you need to use the arrow operator in place of the dot operator. We analyzed here that classes are more superior to structures with a security perspective. If you want to explore more about classes and object-oriented programming in C++, head to this link. If you enjoyed this blog post, share it with a friend!

Exit mobile version