Skip to content

Module 4 · Pointers, Arrays, Strings and Structures — topic 4 of 4

Structures

struct groups related data. In C++ a struct can also have member functions, constructors and default member values; learn aggregates, designated-style initialisation and when to use struct versus class.

Beginner 13 min read·Lesson 16 of 40 in C++ Programming

Learning objectives

  • Define structs with default member initialisers
  • Initialise aggregates with braces
  • Add member functions to a struct

Definition

A struct is a class type whose members are public by default. Like any class it can contain data members, member functions and constructors; a struct with only public data and no constructors is an aggregate.

Introduction

C structs only hold data. C++ structs are full class types: they can have functions, constructors and operators. By convention, struct is used for simple data bundles and class for types with invariants and private data.

Why it matters

Records such as students, products and points are naturally structs.

Understanding that struct and class differ only in default access is a classic interview question.

Detailed explanation

In C++ you can write Student s; — the struct keyword is not needed when using the type.

Default member initialisers: int year = 1; inside the struct gives a default value.

Aggregate initialisation: Point p{3, 4}; assigns members in order. C++20 adds designated initialisers {.x = 3, .y = 4}.

The only language difference between struct and class: members and base classes are public by default in a struct and private by default in a class.

Syntax

C++
struct Student {
int roll = 0;
std::string name;
double cgpa = 0.0;
bool passed() const { return cgpa >= 5.0; }
};
Student s{101, "Asha", 8.9};
  • End the definition with a semicolon.
  • const after a member function means it doesn't modify the object.
  • Structs can be stored in vectors and sorted.

Code examples

An aggregate struct

C++
#include <iostream>
struct Point {
double x = 0, y = 0;
};
int main() {
Point a{3, 4};
Point origin;
std::cout << a.x << ',' << a.y << " and " << origin.x << ',' << origin.y << '\n';
return 0;
}
Output
3,4 and 0,0

A struct with a member function

C++
#include <cmath>
#include <iostream>
struct Point {
double x = 0, y = 0;
double distance_to(const Point& o) const { return std::hypot(x - o.x, y - o.y); }
};
int main() {
Point a{0, 0}, b{3, 4};
std::cout << a.distance_to(b) << '\n';
return 0;
}
Output
5

More examples

Sorting a vector of structs

C++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Student {
int roll;
std::string name;
double cgpa;
};
int main() {
std::vector<Student> cls{{103, "Lakshmi", 9.3}, {101, "Asha", 8.9}, {102, "Vikram", 7.8}};
std::sort(cls.begin(), cls.end(), [](const Student& a, const Student& b) { return a.cgpa > b.cgpa; });
for (const auto& [roll, name, cgpa] : cls)
std::cout << roll << ' ' << name << ' ' << cgpa << '\n';
return 0;
}
Output
103 Lakshmi 9.3
101 Asha 8.9
102 Vikram 7.8

Step-by-step explanation

  • The vector is initialised with three aggregate Student values.
  • std::sort takes a lambda that orders by CGPA descending.
  • Structured bindings unpack each struct in the range-for.
  • Lambdas are covered fully in the Modern C++ module.

Expected output

Running “Sorting a vector of structs” prints exactly:

TextOutput
103 Lakshmi 9.3
101 Asha 8.9
102 Vikram 7.8

Practical applications

  • Configuration records are structs.
  • Game engines use structs for vectors, colours and vertices.
  • Network messages map to structs.

Best practices

  • Use struct for passive data; class when invariants must be protected.
  • Give members default values.
  • Mark read-only member functions const.

Common mistakes

Forgetting the semicolon

Avoid

struct P { int x; }
int main() {}

Prefer

struct P { int x; };
int main() {}

A struct definition must end with ;.

Modifying in a const member function

Avoid

struct C { int n = 0; void inc() const { ++n; } };

Prefer

struct C { int n = 0; void inc() { ++n; } };

A const member function promises not to change the object.

Important notes

  • Aggregates lose aggregate status when you add constructors or private data.
  • Structured bindings work with public data members (C++17).

Key takeaways

  • C++ structs are classes with public default access.
  • Default member initialisers give members starting values.
  • Structs work naturally with containers and algorithms.

Try it yourself

  1. 1
    Define struct Book with title, author and price, store five in a vector and print the cheapest.
  2. 2
    Add a member function total() to a struct Invoice holding item quantities and prices.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is the only language difference between struct and class?
  • BeginnerWhat is printed?
  • BeginnerWhy does `struct P { int x; } int main() {}` fail to compile?
Practise this topic