Lesson 106 +10 XP

Structures

Structures

A struct (short for structure) groups several variables together into one new type. Instead of juggling a handful of unrelated values, you carry one object that holds them all.

Defining a struct

#include <iostream>
using namespace std;

struct Car {
  string brand;
  int year;
};
  • struct says "I am building a struct".
  • Car is the name of the new type.
  • Inside the braces live the members: brand (a string) and year (an int).
  • Do not forget the semicolon ; right after the closing brace.

Declaring an object

Once the struct is defined, declare a variable of that type:

int main() {
  Car myCar;   // an object named myCar
  return 0;
}

Assigning to members

Put values into the object with the dot operator .:

myCar.brand = "BMW";
myCar.year = 1999;
  • myCar.brand means "the brand member of myCar".
  • Each assignment fills one slot inside the object.

Reading members back

Use the same dot to print or use a member:

cout << myCar.brand << " " << myCar.year << endl;   // BMW 1999

Multiple objects

A struct is a blueprint. You can build many objects, and each one keeps its own data:

Car carObj1;
carObj1.brand = "BMW";
carObj1.year = 1999;

Car carObj2;
carObj2.brand = "Ford";
carObj2.year = 1992;

cout << carObj2.brand << endl;   // Ford

Changing carObj1 never touches carObj2 - they are independent ships with their own members.

TL;DR

  • A struct groups several values into one new type.
  • Define with struct Name { members }; - the semicolon matters.
  • Create objects: Car myCar;.
  • Assign or read members with the dot: myCar.brand = "BMW";.
  • Every object owns its own copy of the members.