×

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of comparable data kinds at contiguous memory regions in C++.

Structures in C++, unlike Arrays, are user-defined data types that are used to hold groups of objects of dissimilar data types.

In C++, what is a Struct?

A Struct is a data structure in C++ that may be used to hold pieces of several data types together. A C++ structure is a programmer-defined data type. The structure provides a data type that may be used to aggregate objects of various data types into an individual data type.

Example:

Consider storing information about someone, such as their name, standard and roll number. To keep the data independently, you may construct variables such as name, standard, and roll_num.

Although, we would most probably be needing to keep the same data for a greater amount of people in the future. It indicates that distinct variables will be established for different people. Name1, standard1, roll_num1, and so forth. This is a compilation of all linked data under one name i.e. Info which is a struct. Hence, it is preferable to construct a struct to avoid this.

When should a Structure Be Used?

Here are a few reasons why you should use structure in C++ :

  • When we want to keep elements of many data types in one data type, we use a struct.
  • Structs in C++ are value types rather than reference types. If we don't plan to change our data after it's created, we use a struct.

How to initialize a struct in C++?

The keyword struct, accompanied by an identifier, is used to build a C++ structure. The identifier will become the struct's name. The syntax for creating a C++ struct is as follows:

Syntax:

struct struct_names  
{  
     // structure data members
}   

The struct keyword is used in the above syntax. The struct_names is the structure's name. Curly brackets are used to add the struct elements. These distinct individuals  more often be from various different data categories.

Example:

struct Student  
{  
    char name[40];  
     int standard;  
     int roll_num;  
} 

Explanation:

Student is a three-membered structure in the example above. Name, standard and roll_num are among the members. This structure is built with char data type for name, integer datatype for standard and integer datatype for roll_num also. Memory will be allocated only after a variable will be appended to the struct.

Creating instances for a struct:

We generated a struct called Student in the preceding example. We can make a struct variable like this:

Student st;

The struct variable st is of the type Student. This variable can be used to access the struct's members.

Accessing the members of a struct:

We utilise the struct instance and the dot “.” operator to access the element of the struct. The member access operator is represented by a period between the name of the structure variable and the name of the structure member we want to access. To define variables of the structure type, we'd use the term struct. To get the member standard of struct Student :

Example:

st.standard = 8;

Explanation:

We used the struct's instance st, to get the member standard of struct Student. After that, we changed the member's standard to 8.

Example:

#include <iostream>    
using namespace std;
struct Student
{
	int standard;
	int roll_num;
};
int main(void) {
	struct Student st;
	st.standard = 8;
	st.roll_num = 21;
	cout << "Student’s standard: " << st.standard << endl;
	cout << "Student’s roll number: " << st.roll_num << endl;


	return 0;
}

Output:

Student’s standard: 8
Student’s roll number: 21

Explanation:

In the above example, we created a struct Student with two struct members of integer type namely standard and roll_num. Then in the main() function we created an instance st of struct Student. Using that instance, we provided values for standard and roll_num and they were printed as required.

Structure pointer:

A pointer that refers to a structure can be created. It's analogous to how pointers to native data types like as int, float, double, and so on are produced. In C++, a pointer is used to hold a memory address. Members are accessed using the arrow (->) operator rather than the dot (.) operator when we have a pointer pointing to a structure.

Example:

#include <iostream>
using namespace std;


struct Lengths
{
	int mtrs;
	float ctmtrs;
};


int main()
{
	Lengths *ptr, z;


	ptr = &z;


	cout << "Enter length in meters: ";
	cin >> (*ptr).mtrs;
	cout << "Enter length in centimeters: ";
	cin >> (*ptr).ctmtrs;
	cout << "Length = " << (*ptr).mtrs << " meters " << (*ptr).ctmtrs << " centimeters";


	return 0;
}

Output:

Enter length in meters: 10
Enter length in centimeters: 34
Length = 10 meters 34 centimeters

Explanation:

In the above example, we created a struct Lengths with two struct members of integer type namely mtrs and ctmtrs. Then in the main() function we created a pointer variable *ptr and a normal variable z of type Lengths whose address is stored in the pointer variable. Using that instance, we asked values for mtrs and ctmtrs and they were printed as required.

Passing Struct as function argument:

A struct can be sent as an argument to a function. This is proceeded in the same way as the passing of a standard argument. A function can also be supplied struct variables. When you do need to present the data of struct members, this is an excellent example.

Example:

#include<iostream>
using namespace std;


struct Student
{
	int standard;
	int roll_num;
};


void func(struct Student st);


int main()
{
	struct Student st;


	st.standard = 9;
	st.roll_num = 24;


	func(st);
	return 0;
}
void func(struct Student st)
{
	cout << "Student’s standard: " << st.standard << endl;
	cout << "Student’s roll number: " << st.roll_num << endl;
}

Output:

Student’s standard: 9
Student’s roll number: 24

Explanation:

In the above example, we created a struct Student with two struct members of integer type namely standard and roll_num. Then created a function func() that takes the instance st of struct Student as the argument. Then in the main() function we created an instance st of struct Student. When that function func() will be called the instance of the struct st will be passed as an argument and using that instance, we provided values for standard and roll_num and they were printed as required.

Drawbacks of C++ Structure:

C++ Structures have the following drawbacks:

  • Built-in data types cannot be used with the struct data type.
  • On structural variables, operators like +, -, and others are not allowed.
  • Data concealing is not possible with structures. Any function, regardless of its scope, can access the members of a structure.
  • Static members cannot be defined within the structural body.
  • Constructors cannot be built inside a struct.

Differences between a Struct and a class:

ParametersStructClass
DefinitionA structure is a collection of variables of different data kinds with the same name.A class in C++ is a single structure that contains a collection of linked variables and functions.
Declared asstruct structures_name{ type structs_member1; type struct_member2; . type struct_memberN; };  class class_names{ data members;   members func; };  
GeneralEvery member is set to 'public' when no access specifier is supplied.Every member is set to 'private' if no access specifier is given.
ObjectiveData classification.Further inheritance and data abstraction.
InstancesThe 'structure variable' is the name for a structure instance.The term 'object' refers to a class instance.
Used forIt's for tiny bits of information.It stores a large quantity of data.
Memory AllocationThe stack is used to allocate memory.The heap is where memory is allocated.
Constructor and DestructorIt's possible that it only has a parameterized constructor.It might include any number of both, constructors and destructors.
ReusabilityNot reusableFully reusable
Initialization of members variablesNot allowed.Allowed.
Default empty size0 Bytes1 Byte
Garbage collectionSince it employs pass by value, this isn't feasible.Since it utilises pass by reference, it's possible.
Memory managementPoorEffective

Conclusion:

  • A struct is a data structure for storing data pieces of various kinds.
  • A struct contains data elements of diverse kinds, while an array contains data items of the same type.
  • When the data pieces are not supposed to change value, a struct must be utilised.
  • The dot (.) operator is used to access the data members of a struct.
  • We must first build a struct instance.
  • The struct keyword is used to build a C++ struct.
  • Pointers referring to structs are constructed in the same way that pointers pointing to normal types are.
  • A struct could be supplied to a function as an argument in the same manner that regular functions are.

Related Topics

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

C++ Scope of Variables

In this tutorial, we will explore about the scope of variables in c++ programming language. And also, how it works in a program. What is Scope? The range of applications for something...

4 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

3 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

C++ operator

In this article, we will discuss about the operators in C++ with their types and examples. An operator is specially a symbol that tells compiler to perform specific manipulation. C++ contains...

5 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

C++ 11 vs C++ 14 vs C++ 17

C++ is a language that is used to create a high-performance application. C++ 11, C++ 14, and C++ 17 are the different version of C++. There are some differences between...

1 minute read.

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 minutes read.

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

How to create a table in C++

C++ is a programming language that has evolved as an improvement of c language. It includes an object-oriented archetype. C++ programming language is a compiled language that complies with the...

3 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

Is it fine to write void main() or main() in C/C++?

In C programming language: The default function return type in the C programming language is "int," which implies that main() will always return an integer value. In C, the void main()...

3 minutes read.