×

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

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

Computing index using Pointers Returned by STL Functions in C++

In this tutorial we will learn how to compute index using pointers which returned by STL functions in C++. Many built-in C++ functions return pointers to memory places that provide...

2 minutes read.

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using...

4 minutes read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 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.

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

Priority Queue in C++

Priority Queue in C++ Introduction: We have already come across Queues by concluding that they are linear data structures that follow FIFO (First-In-First-Out) approach. We had also discussed the syntax of queues...

4 minutes read.

C++ Virtual Destructor

In C++, a destructor is a class member function that is used to free up space or remove an object of the class that has gone out of scope. The...

4 minutes read.

How to Setup Environment for C++ Programming on Mac

Mac OS X code Installation There are so many environments available for C++. We are going to install jGrasp and Xcode in our mac operating system. Instruction for installation of jGrasp and...

2 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

Depth First Search Program to Traverse a Graph in C++

Depth First Search (DFS) is a technique that is used for transversing the graph. The process of Depth First Search (DFS) starts from the root node and then next comes...

6 minutes read.