Ugenz Academy/Tutorial

Structure

15 min read2,805 words

Reading progress

Keep learning

Structures in C++

1. Introduction

A structure (struct) in C++ is a user-defined data type that allows us to group different types of related data under one name.

For example, information about a student may contain:

  • Name → string
  • Age → int
  • GPA → float

A structure allows us to store all these values together as one object.

2. Definition of Structure

A structure is a user-defined data type that groups variables of different data types into a single unit.

Simple Definition

A structure is a collection of related variables of different data types stored under one name.

Example

struct Student { string name; int age; float gpa; };

Here, Student is a structure containing three members:

  • name
  • age
  • gpa

3. Why Use Structures?

Structures are useful when we need to store multiple pieces of related information.

For example, instead of creating separate variables:

string name; int age; float gpa;

we can group them:

struct Student { string name; int age; float gpa; };

This makes programs:

  • Organized
  • Easier to understand
  • Easier to maintain
  • Suitable for storing records
  • Useful for handling collections of related data

4. Syntax of Structure

The general syntax is:

struct StructureName { dataType member1; dataType member2; dataType member3; };

Example

struct Student { string name; int age; float gpa; };

Important

A semicolon ; is required after the closing brace:

};

5. Creating a Structure Variable

After defining a structure, we can create its variables.

struct Student { string name; int age; float gpa; }; int main() { Student s1; return 0; }

Here:

  • Student → structure type
  • s1 → structure variable

6. Accessing Structure Members

The dot (.) operator is used to access structure members.

Example

#include <iostream> #include <string> using namespace std; struct Student { string name; int age; float gpa; }; int main() { Student s1; s1.name = "Anuradha"; s1.age = 21; s1.gpa = 3.36; cout << "Name: " << s1.name << endl; cout << "Age: " << s1.age << endl; cout << "GPA: " << s1.gpa << endl; return 0; }

Output

Name: Anuradha Age: 21 GPA: 3.36

7. Structure Initialization

A structure can be initialized when its variable is created.

#include <iostream> #include <string> using namespace std; struct Student { string name; int age; float gpa; }; int main() { Student s1 = {"Anuradha", 21, 3.36}; cout << s1.name << endl; cout << s1.age << endl; cout << s1.gpa << endl; return 0; }

Output

Anuradha 21 3.36

8. Multiple Structure Variables

We can create multiple variables of the same structure type.

#include <iostream> #include <string> using namespace std; struct Student { string name; int age; }; int main() { Student s1, s2; s1.name = "Anuradha"; s1.age = 21; s2.name = "Ram"; s2.age = 22; cout << s1.name << " " << s1.age << endl; cout << s2.name << " " << s2.age << endl; return 0; }

Output

Anuradha 21 Ram 22

9. Taking Structure Data from User

We can use cin to take structure member values from the user.

#include <iostream> #include <string> using namespace std; struct Student { string name; int age; float gpa; }; int main() { Student s; cout << "Enter name: "; cin >> s.name; cout << "Enter age: "; cin >> s.age; cout << "Enter GPA: "; cin >> s.gpa; cout << "\nStudent Details\n"; cout << "Name: " << s.name << endl; cout << "Age: " << s.age << endl; cout << "GPA: " << s.gpa << endl; return 0; }

Sample Output

Enter name: Anuradha Enter age: 21 Enter GPA: 3.36 Student Details Name: Anuradha Age: 21 GPA: 3.36

10. Structure with getline()

If the name contains spaces, use getline().

#include <iostream> #include <string> using namespace std; struct Student { string name; int age; }; int main() { Student s; cout << "Enter full name: "; getline(cin, s.name); cout << "Enter age: "; cin >> s.age; cout << "\nName: " << s.name << endl; cout << "Age: " << s.age << endl; return 0; }

Sample Output

Enter full name: Anuradha Kumari Mandal Enter age: 21 Name: Anuradha Kumari Mandal Age: 21

11. Array of Structures

An array of structures is used to store multiple records of the same structure type.

Example

#include <iostream> #include <string> using namespace std; struct Student { string name; int age; }; int main() { Student students[3]; students[0] = {"Anuradha", 21}; students[1] = {"Ram", 22}; students[2] = {"Sita", 20}; for (int i = 0; i < 3; i++) { cout << "Name: " << students[i].name << endl; cout << "Age: " << students[i].age << endl; cout << endl; } return 0; }

Output

Name: Anuradha Age: 21 Name: Ram Age: 22 Name: Sita Age: 20

12. Structure with Functions

A structure can be passed to a function.

Example

#include <iostream> #include <string> using namespace std; struct Student { string name; int age; }; void display(Student s) { cout << "Name: " << s.name << endl; cout << "Age: " << s.age << endl; } int main() { Student s = {"Anuradha", 21}; display(s); return 0; }

Output

Name: Anuradha Age: 21

13. Passing Structure by Reference

A structure can be passed by reference using &.

#include <iostream> #include <string> using namespace std; struct Student { string name; int age; }; void display(const Student& s) { cout << "Name: " << s.name << endl; cout << "Age: " << s.age << endl; } int main() { Student s = {"Anuradha", 21}; display(s); return 0; }

Using const Student& avoids making an unnecessary copy and prevents the function from modifying the original structure.

14. Pointer to Structure

A pointer can point to a structure variable.

#include <iostream> #include <string> using namespace std; struct Student { string name; int age; }; int main() { Student s = {"Anuradha", 21}; Student* ptr = &s; cout << ptr->name << endl; cout << ptr->age << endl; return 0; }

Output

Anuradha 21

15. Dot (.) vs Arrow (->) Operator

When using a normal structure variable, use the dot operator:

s.name

When using a pointer to a structure, use the arrow operator:

ptr->name

Example

Student s; Student* ptr = &s; s.age = 21; ptr->age = 22;

The expression:

ptr->age

is equivalent to:

(*ptr).age

16. Nested Structures

A structure can contain another structure as a member.

Example

#include <iostream> #include <string> using namespace std; struct Address { string city; int ward; }; struct Student { string name; int age; Address address; }; int main() { Student s; s.name = "Anuradha"; s.age = 21; s.address.city = "Janakpur"; s.address.ward = 8; cout << "Name: " << s.name << endl; cout << "Age: " << s.age << endl; cout << "City: " << s.address.city << endl; cout << "Ward: " << s.address.ward << endl; return 0; }

Output

Name: Anuradha Age: 21 City: Janakpur Ward: 8

17. Structure Containing an Array

A structure can contain an array.

#include <iostream> #include <string> using namespace std; struct Student { string name; int marks[3]; }; int main() { Student s = {"Anuradha", {80, 85, 90}}; cout << "Name: " << s.name << endl; cout << "Marks: "; for (int i = 0; i < 3; i++) { cout << s.marks[i] << " "; } return 0; }

Output

Name: Anuradha Marks: 80 85 90

18. Structure with Different Data Types

One major feature of structures is that they can contain different data types.

struct Employee { int id; string name; float salary; char grade; bool permanent; };

Here the structure contains:

MemberData Type
idint
namestring
salaryfloat
gradechar
permanentbool

19. Using typedef with Structure

In older C/C++ code, typedef may be used to create a shorter name.

typedef struct { string name; int age; } Student;

Now we can write:

Student s;

instead of defining a separate structure name.

Modern C++ Recommendation

In modern C++, simply use:

struct Student { string name; int age; };

Then:

Student s;

is already sufficient.

20. Structure and class

C++ structures and classes are very similar.

Example:

struct Student { string name; };

and:

class Student { public: string name; };

Both can contain:

  • Variables
  • Functions
  • Constructors
  • Access specifiers
  • Static members
  • Other structures/classes

Main Difference

The default access level is different.

Featurestructclass
Default accesspublicprivate
Common useData groupingObject-oriented design
Functions allowedYesYes
Constructors allowedYesYes
Inheritance allowedYesYes

Example:

struct Student { string name; // public by default };

While:

class Student { string name; // private by default };

21. Structure with Functions as Members

In C++, a structure can also contain member functions.

#include <iostream> using namespace std; struct Student { string name; int age; void display() { cout << "Name: " << name << endl; cout << "Age: " << age << endl; } }; int main() { Student s; s.name = "Anuradha"; s.age = 21; s.display(); return 0; }

Output

Name: Anuradha Age: 21

This shows that C++ structures are more powerful than traditional C structures.

22. Structure with Constructor

A structure can have a constructor.

#include <iostream> #include <string> using namespace std; struct Student { string name; int age; Student(string n, int a) { name = n; age = a; } void display() { cout << "Name: " << name << endl; cout << "Age: " << age << endl; } }; int main() { Student s("Anuradha", 21); s.display(); return 0; }

Output

Name: Anuradha Age: 21

23. Real-Life Example of Structure

Structures are useful for representing real-world records.

For example, a student record can contain:

Student ├── Name ├── Roll Number ├── Age ├── Address └── GPA

C++ representation:

struct Student { string name; int rollNo; int age; string address; float gpa; };

Similarly, we can create structures for:

  • Employee
  • Customer
  • Product
  • Book
  • Bank account
  • Vehicle
  • Patient
  • College records

24. Complete Student Record Program

#include <iostream> #include <string> using namespace std; struct Student { string name; int rollNo; float gpa; }; int main() { Student s; cout << "Enter student name: "; getline(cin, s.name); cout << "Enter roll number: "; cin >> s.rollNo; cout << "Enter GPA: "; cin >> s.gpa; cout << "\n--- Student Record ---\n"; cout << "Name: " << s.name << endl; cout << "Roll Number: " << s.rollNo << endl; cout << "GPA: " << s.gpa << endl; return 0; }

Sample Output

Enter student name: Anuradha Kumari Mandal Enter roll number: 101 Enter GPA: 3.36 --- Student Record --- Name: Anuradha Kumari Mandal Roll Number: 101 GPA: 3.36

25. Advantages of Structures

  1. Groups related data Different data types can be stored together.

  2. Improves organization Related information is kept in one place.

  3. Easy to manage records Useful for student, employee, product, and customer records.

  4. Supports arrays Arrays of structures can store many records.

  5. Supports functions Structures can be passed to and returned from functions.

  6. Supports pointers Pointers can point to structures.

  7. Supports OOP features C++ structures can contain functions, constructors, and access specifiers.

26. Disadvantages of Structures

  1. Large structures may consume significant memory.
  2. Complex structures can become difficult to manage.
  3. Copying large structures can be inefficient.
  4. Poorly designed structures can make programs harder to maintain.
  5. For complex object-oriented programs, classes may provide clearer design.

27. Important Operators Used with Structures

OperatorPurposeExample
.Access member using objects.name
->Access member using pointerptr->name
&Get address&s
*Dereference pointer(*ptr).name

28. Structure vs Array

StructureArray
Can contain different data typesNormally contains elements of the same type
Groups related informationStores multiple values
Members have different namesElements use indexes
Uses . to access membersUses [] to access elements
Example: student recordExample: list of marks

Structure

struct Student { string name; int age; float gpa; };

Array

int marks[5];

29. Structure vs Union

StructureUnion
All members can hold values at the same timeNormally only one member is used at a time
Each member has separate storageMembers share the same memory
Size is generally enough for all members plus alignmentSize is based mainly on its largest member plus alignment
Useful for recordsUseful when memory sharing is important

Example structure:

struct Data { int i; float f; char c; };

Example union:

union Data { int i; float f; char c; };

30. Common Errors

Error 1: Forgetting the Semicolon

Incorrect:

struct Student { string name; }

Correct:

struct Student { string name; };

Error 2: Accessing Members Incorrectly

Incorrect:

Student s; s->name = "Anuradha";

-> is used with a pointer.

Correct:

s.name = "Anuradha";

Error 3: Using -> with a Normal Variable

Incorrect:

Student s; s->name;

Correct:

s.name;

Error 4: Using . with a Pointer

Incorrect:

Student* ptr = &s; ptr.name;

Correct:

ptr->name;

Error 5: Missing Header Files

For string, include:

#include <string>

For input and output:

#include <iostream>

31. Important Points to Remember

  • A structure is a user-defined data type.
  • Use the struct keyword to define a structure.
  • A structure can contain members of different data types.
  • A semicolon is required after the structure definition.
  • Use . to access members through a normal structure variable.
  • Use -> to access members through a structure pointer.
  • Structures can be used with arrays.
  • Structures can be passed to functions.
  • Structures can contain arrays and other structures.
  • C++ structures can contain member functions and constructors.
  • The default access level of a struct is public.
  • The default access level of a class is private.

32. Quick Syntax Reference

Define a structure

struct Student { string name; int age; float gpa; };

Create an object

Student s;

Initialize an object

Student s = {"Anuradha", 21, 3.36};

Access members

s.name; s.age; s.gpa;

Structure pointer

Student* ptr = &s;

Access through pointer

ptr->name;

Array of structures

Student students[10];

33. Summary

A structure in C++ is a user-defined data type used to group related variables of different data types under one name.

For example:

struct Student { string name; int age; float gpa; };

We can then create a structure object:

Student s = {"Anuradha", 21, 3.36};

and access its members using:

cout << s.name; cout << s.age; cout << s.gpa;

Structures are especially useful for representing real-world records, such as students, employees, customers, products, books, and vehicles.

Conclusion

Structures are an important feature of C++ for organizing related data. They make it possible to combine different data types into a single meaningful unit. C++ also extends structures beyond simple data grouping by allowing them to contain functions, constructors, pointers, arrays, and nested structures.

Understanding structures provides a strong foundation for learning classes, objects, and object-oriented programming in C++.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy