Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C++ Structures

A structure groups values that belong together, such as the name, roll number and marks of a student. In C++ a struct defines a new type, and you do not need to write struct again when you use it.

Defining and using a struct

#include <iostream>
#include <string>

struct Student {
    std::string name;
    int roll = 0;          // default value
    double marks = 0.0;
};

int main() {
    Student s;
    s.name = "Asha";
    s.roll = 1;
    s.marks = 84.5;
    Student t{"Meera", 2, 91.5};      // all members at once
    std::cout << s.name << " " << s.marks << "\n";
    std::cout << t.name << " " << t.marks << "\n";
    return 0;
}
Output
Asha 84.5
Meera 91.5

Members are reached with a dot. A std::string member can be assigned with =, unlike a C character array. Default values (int roll = 0;) are used when a member is not given.

A vector of structs

#include <iostream>
#include <string>
#include <vector>

struct Student {
    std::string name;
    int roll;
    double marks;
};

int main() {
    std::vector<Student> cls = {{"Asha", 1, 84.5}, {"Meera", 2, 91.5}, {"Ravi", 3, 77.0}};
    const Student* best = &cls[0];
    for (const Student& s : cls) {
        if (s.marks > best->marks) best = &s;
    }
    std::cout << "Best: " << best->name << " with " << best->marks << "\n";
    return 0;
}
Output
Best: Meera with 91.5

With a pointer to a structure, members are reached with the arrow ->.

Passing structs to functions

Pass a struct by const& to read it without copying, and by & to change it:

#include <iostream>

struct Account {
    int number;
    double balance;
};

void deposit(Account& acc, double amount) {
    acc.balance += amount;
}

void print(const Account& acc) {
    std::cout << "Account " << acc.number << ": " << acc.balance << "\n";
}

int main() {
    Account a{1001, 500};
    deposit(a, 250);
    print(a);
    return 0;
}
Output
Account 1001: 750

struct and class

In C++ a struct is the same as a class (see Classes), except that its members are public by default. By convention, struct is used for simple groups of data, and class for types with their own rules and private data.

Printing a struct

std::cout << s; does not work for your own struct until you tell C++ how to print it. Writing an operator<< for it is covered in Operator Overloading; until then, print the members one by one or write a small print function.

Practice exercises

  1. Define a Book struct with a title, an author and a price; fill a vector of three and print the cheapest.
  2. Write a function that raises a book's price by 10 percent, taking the book by reference.
  3. Add a nested Date struct to Book and print each publication date.