C++ Struct With Example

What is a Struct in C++?

A STRUCT is a C++ data structure that can be used to store together elements of different data types. In C++, a structure is a user-defined data type. The structure creates a data type for grouping items of different data types under a single data type.

For example:

Suppose you need to store information about someone, their name, citizenship, and age. You can create variables like name, citizenship, and age to store the data separately.

However, you may need to store information about many persons in the future. It means variables for different individuals will be created. For example, name1, citizenship1, age1 etc. To avoid this, it’s better to create a struct.

In this C++ tutorial, you will learn:

When to use a Structure?

Here are some reasons using structure in C++.

  • Use a struct when you need to store elements of different data types under one data type.
  • C++ structs are a value type rather than being a reference type. Use a struct if you don’t intend to modify your data after creation.

C++ Struct Initialization

To create a C++ structure, we use the struct keyword, followed by an identifier. The identifier becomes the name of the struct. Here is the syntax for creation of a C++ struct:

Syntax:

struct struct_name  
{  
     // struct members
}   

In the above syntax, we have used the struct keyword. The struct_name is the name of the structure.

The struct members are added within curly braces. These members probably belong to different data types.

For example:

struct Person  
{  
    char name[30];  
     int citizenship;  
     int age;  
}  

In the above example, Person is a structure with three members. The members include name, citizenship, and age. One member is of char data type, while the remaining 2 are integers when a structure is created, memory is not allocated. Memory is only allocated after a variable is added to the struct.

Creating Struct Instances

In the above example, we have created a struct named Person. We can create a struct variable as follows:

Person p;

The p is a struct variable of type Person. We can use this variable to access the members of the struct.

Accessing Struct Members

To access the struct members, we use the instance of the struct and the dot (.) operator. For example, to access the member age of struct Person:

p.age = 27;

We have accessed the member age of struct Person using the struct’s instance, p. We have then set the value of the member age to 27.

Example 1:

#include <iostream>    
using namespace std;
struct Person
{
	int citizenship;
	int age;
};
int main(void) {
	struct Person p;
	p.citizenship = 1;
	p.age = 27;
	cout << "Person citizenship: " << p.citizenship << endl;
	cout << "Person age: " << p.age << endl;

	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in our program to use the functions defined in it.
  2. Include the std namespace to use its classes without calling it.
  3. Create a struct named Person.
  4. The beginning of the struct body.
  5. Create a struct member named citizenship of type integer.
  6. Create a struct member named age of type integer.
  7. End of the struct body.
  8. Call the main() function. The program logic should be added within the body of this function.
  9. Create an instance of the struct Person and giving it the name p.
  10. Set the value of struct member citizenship to 1.
  11. Set the value of struct member age to 27.
  12. Print the value of the struct member citizenship on the console alongside some other text.
  13. Print the value of the struct member age on the console alongside some other text.
  14. The program should return a value if it runs successfully.
  15. End of the main() function.

Pointers to Structure

It’s possible to create a pointer that points to a structure. It is similar to how pointers pointing to native data types like int, float, double, etc. are created. Note that a pointer in C++ will store a memory location.

Example 2:

#include <iostream>
using namespace std;

struct Length
{
	int meters;
	float centimeters;
};

int main()
{
	Length *ptr, l;

	ptr = &l;

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

	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in our program in order to use its functions.
  2. Include the std namespace in our program to use its classes without calling it.
  3. Create a struct named Length.
  4. Start of the body of the struct Length.
  5. Create a struct member named meters of integer data type.
  6. Create a struct member named centimeters of type integer.
  7. End of the body of the struct Length.
  8. Call the main() function.
  9. Start of the body of the main() function.
  10. Create a pointer variable *ptr and normal variable l of type Length.
  11. Store the address of variable l in our pointer variable.
  12. Display a message on the console, asking the user to enter the value for variable meters.
  13. Read the value entered by the user via the keyboard. The member function meters is here accessed using the pointer variable.
  14. Display a message on the console, asking the user to enter the value for variable centimeters.
  15. Read the value entered by the user via the keyboard. The member function centimeters is here accessed using the pointer variable.
  16. Display the values read from the user on the console alongside some other text.
  17. The program must return a value upon successful execution.
  18. End of the body of the main() function.

Struct as Function Argument

You can pass a struct to a function as an argument. This is done in the same way as passing a normal argument. The struct variables can also be passed to a function. A good example is when you need to display the values of struct members. Let’s demonstrates this:

Example 3:

#include<iostream>
using namespace std;

struct Person
{
	int citizenship;
	int age;
};

void func(struct Person p);

int main()
{
	struct Person p;

	p.citizenship = 1;
	p.age = 27;

	func(p);
	return 0;
}
void func(struct Person p)
{
	cout << " Person citizenship: " << p.citizenship<<endl;
	cout << " Person age: " << p.age;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file into our file. We will then use its functions without getting errors.
  2. Include the std namespace in our program to use its classes. We will not need to call the namespace to use its classes.
  3. Create a struct named Person.
  4. Start of the body of the struct Person.
  5. Create a member of struct Person. The member is named citizenship and is of type integer.
  6. Create a member of struct Person. The member is named age and is of type integer.
  7. End of the body of struct Person.
  8. Create a function that takes the instance of struct Person, p, as the argument.
  9. Call the main function. The { marks the beginning of the body of main() function.
  10. Create an instance of struct Person and giving it the name p.
  11. Access the struct member variable citizenship using the instance of the struct, p, and assigning it the value 1.
  12. Access the struct member variable age using the instance of the struct, p, and assigning it the value 27.
  13. Call the function and passing to it the instance of the struct Person, p, as the argument.
  14. The function must return a value upon successful execution.
  15. End of the body of the main() function.
  16. Create the body of the function.
  17. The start of the body of the function.
  18. Access the struct member citizenship value and printing it on the console alongside other text.
  19. Access the struct member age value and printing it on the console alongside other text.
  20. End of the function body.

Limitation of a C++ structure

The following are the limitations of structures:

  • The struct data type cannot be treated like built-in data types.
  • Operators like + -, and others cannot be used on structure variables.
  • Structures don’t support data hiding. The members of a structure can be accessed by any function regardless of its scope.
  • Static members cannot be declared inside the structure body.
  • Constructors cannot be created inside a structure.

Summary:

  • A struct is a data structure that stores data elements belonging to different types.
  • Whereas an array stores data elements of a similar type, a struct stores data elements of different types.
  • A struct should be used when the data elements are not expected to change value.
  • The members of a struct are accessed using the dot (.) operator.
  • We have to create an instance of the struct.
  • To create a C++ struct, we use the struct keyword.
  • Pointers pointing to a struct are created similarly to how pointers which is pointing to regular types are created.
  • A struct can be passed as an argument to a function in the same way ordinary functions are passed.