Labs ICT
Pro Login

Structs

A struct (short for structure) groups related variables together into a single type. It is like creating a custom data type that holds multiple pieces of information. Unlike an array where every element must be the same type, a struct can hold different types.

Defining and Using a Struct

You define a struct with the struct keyword, followed by the members inside curly braces. Each member can be any valid type:

#include <iostream>
#include <string>

struct Student {
  std::string name;
  int age;
  double gpa;
};

int main() {
  Student s1;
  s1.name = "Blessing";
  s1.age = 20;
  s1.gpa = 3.8;

  Student s2 = {"Chidi", 22, 3.5};

  std::cout << s1.name << " is " << s1.age
            << " years old, GPA: " << s1.gpa << "\n";
  std::cout << s2.name << " is " << s2.age
            << " years old, GPA: " << s2.gpa << "\n";
  return 0;
}

You access members with the dot operator .. You can initialize a struct with a brace-enclosed list — the values go in the same order as the member declarations.

Struct vs Class

In C++, struct and class are almost identical. The only difference is the default access level — struct members are public by default, class members are private. Many programmers use structs for simple data containers and classes for objects with behavior:

#include <iostream>
#include <string>

struct Point {
  int x;
  int y;
};

class Rectangle {
  int width;
  int height;
public:
  Rectangle(int w, int h) : width(w), height(h) {}
  int area() { return width * height; }
};

int main() {
  Point p = {10, 20};
  Rectangle rect(5, 8);

  std::cout << "Point: (" << p.x << ", " << p.y << ")\n";
  std::cout << "Area: " << rect.area() << "\n";
  return 0;
}

Point is a struct with public members — no getters needed. Rectangle is a class with private data and a public method. Both are valid, just different conventions.

Structs with Functions

Structs can have member functions too. In fact, a struct in C++ can do everything a class can do, including constructors:

#include <iostream>
#include <string>

struct Book {
  std::string title;
  std::string author;
  int pages;

  void display() {
    std::cout << "\"" << title << "\" by " << author
              << ", " << pages << " pages\n";
  }
};

int main() {
  Book b = {"Things Fall Apart", "Chinua Achebe", 209};
  b.display();
  return 0;
}