C++ Struct With Example

⚡ Smart Summary

Struct in C++ is a user-defined data type that groups elements of different data types under a single name, letting one variable hold related values such as a person name, citizenship, and age together.

  • 📦 Different data types: A struct groups variables of unlike types under one user-defined name.
  • 🔑 struct keyword: Define a structure with the struct keyword, then list members inside curly braces.
  • 🧱 Creating instances: Writing Person p makes a struct variable and allocates its memory.
  • 🎯 Dot operator: Read or set any member through the instance, as in p.age = 27.
  • ➡️ Pointers and functions: A struct works with pointers and passes to a function like an ordinary argument.
  • 🤖 AI assistance: GitHub Copilot and other AI assistants scaffold struct definitions and member access from a comment.

C++ Struct

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.

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:

Accessing Struct Members

Here is a screenshot of the code:

Accessing Struct Members

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:

Pointers to Structure

Here is a screenshot of the code:

Pointers to Structure

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:

Struct as Function Argument

Here is a screenshot of the code:

Struct as Function Argument

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.

FAQs

In C++ a struct and a class are almost identical. The only real difference is default access: struct members are public by default, while class members are private. Both support member functions, constructors, and inheritance.

A C struct only holds data, and you must write struct before each variable declaration. A C++ struct can also include member functions, constructors, and access specifiers, and the struct keyword is optional when declaring variables.

Declare the struct, then define an array of it, for example Person people[3]. Each element is a full struct, and you access members with people[0].age. Arrays of structures store many records of the same type together.

A nested structure is a struct declared as a member inside another struct. It groups related sub-data, such as a Date struct placed inside an Employee struct. You reach inner members by chaining the dot operator.

The size is roughly the sum of its members, plus padding the compiler adds for alignment, so sizeof can exceed the raw total. Member functions add nothing. Ordering members by size reduces wasted padding.

Use the arrow operator when you hold a pointer to a struct. Instead of (*ptr).age, the shortcut ptr->age reads the same member. The dot operator works on a direct instance, not a pointer.

Yes. AI coding assistants turn a short prompt or comment into a complete C++ struct, including members, constructors, and field access. Always review the generated data types and alignment, since AI can miss project-specific requirements.

Yes. GitHub Copilot suggests struct definitions, member variables, and dot or arrow access as you type in your editor. It handles repetitive boilerplate well, though you should still verify types, padding, and logic before compiling.

Summarize this post with: