Structures in C++

A structure (struct) in C++ is a user-defined data type that allows grouping variables of different types under a single name. Structures are useful for representing complex data items.

Defining a Structure

Syntax

struct StructureName {
    data_type member1;
    data_type member2;
    // ...
};

Example: Defining and Using a Structure

#include <iostream>
#include <string>

struct Student {
    std::string name;
    int age;
    char grade;
};

int main() {
    Student student1;
    student1.name = "Akila";
    student1.age = 22;
    student1.grade = 'A';
    
    std::cout << "Name: " << student1.name << std::endl;
    std::cout << "Age: " << student1.age << std::endl;
    std::cout << "Grade: " << student1.grade << std::endl;
    return 0;
}

Key Takeaways

  • Structures group variables of different types under a single name.
  • Access structure members using the dot operator (.).
  • Structures enhance code organization and readability.

Initializing Structures

Example: Initialization at Declaration

Student student2 = {"Karthick", 25, 'B'};

Structures and Functions

You can pass structures to functions by value or by reference.

Example: Passing Structure to a Function

void displayStudent(Student s) {
    std::cout << "Name: " << s.name << std::endl;
    std::cout << "Age: " << s.age << std::endl;
    std::cout << "Grade: " << s.grade << std::endl;
}

Key Takeaways

  • Structures can be passed to functions like any other data type.
  • Passing by reference avoids copying the entire structure.
  • Useful for organizing complex data manipulations.