C++ Tutorial

C++ Structures

struct groups related fields under one name: a point, a player, a record.

Related fields, one type

An array stores many values of one type. A struct stores a handful of values that belong together, even if the types differ. A point on a map has an x and a y. A player has a name and a score. Those are not four loose variables. They are one record.

You name the shape first. Then you create variables of that shape. Each variable is a struct object with its own copy of the fields.

Define a struct

The keyword struct, a type name, a brace block of fields, and a semicolon after the closing brace. That last semicolon is easy to forget. The compiler will complain on the next line.

Example

#include <iostream>
using namespace std;

struct Point {
  double x;
  double y;
};

int main() {
  Point p;
  p.x = 3.0;
  p.y = 4.0;
  cout << p.x << ", " << p.y << endl;
  return 0;
}

Put the struct definition above main so the compiler already knows the type when it reaches the function. Fields are public by default in a struct: you can read and write them from main.

The dot operator

p.x means “the x field of p”. The dot does not copy the struct. It selects one member. You can use a field anywhere you would use a variable of that field’s type: print it, add to it, pass it to a later function.

Example

#include <iostream>
#include <string>
using namespace std;

struct Player {
  string name;
  int score;
};

int main() {
  Player hero;
  hero.name = "Nia";
  hero.score = 1200;
  hero.score = hero.score + 50;
  cout << hero.name << " has " << hero.score << endl;
  return 0;
}

string needs #include <string>. Mix types freely inside one struct: numbers, text, booleans. Keep the fields related. A player record should not also store a random file path.

Assign one struct to another

Assignment copies every field. After b = a, the two variables are independent. Changingb.x leaves a.x alone.

Example

#include <iostream>
using namespace std;

struct Point {
  double x;
  double y;
};

int main() {
  Point a;
  a.x = 2.0;
  a.y = 5.0;

  Point b = a;
  b.x = 9.0;

  cout << "a: " << a.x << ", " << a.y << endl;
  cout << "b: " << b.x << ", " << b.y << endl;
  return 0;
}

You can also fill a struct with a brace list in declaration order: Point origin = {0.0, 0.0};. That is a copy of the values into a new object, not a live link to another point.

Many variables, one type

Point is a type you invented, the same way int is a type the language invented. You can declare as many Point variables as you need. You can put structs in arrays later:Point corners[4]; is four points, each with an x and a y.

PieceRole
struct Point { ... };Names the type and lists fields
Point p;Creates one object
p.xReads or writes a field
Point b = a;Copies every field

Struct now, class later

A struct is enough for a record: data you group and pass around. Classes add methods, constructors, and private fields. You do not need those yet. If you catch yourself writing x1, y1,x2, y2, stop and make a Point.

The semicolon after the struct’s closing brace is part of the definition. Functions do not need that extra semicolon after their body. Structs do.

Next: name a small set of choices with an enum instead of magic numbers.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.

Physics

A force with two components

A force in a plane needs Fx and Fy. The magnitude is the same Pythagoras as a displacement: √(Fx² + Fy²). 3 N east and 4 N north is 5 N.

struct keeps the two components under one name so you do not pass fx and fy as unrelated arguments and swap them by mistake.

|F| = √(Fx² + Fy²)

Example

#include <iostream>
#include <cmath>
using namespace std;

struct Force {
  double fx;
  double fy;
};

int main() {
  Force f = {3.0, 4.0};
  double mag = hypot(f.fx, f.fy);
  cout << "|F| = " << mag << " N" << endl;
  return 0;
}

Biology

Temperature and pulse together

A nurse does not store a temperature in one notebook and a pulse in another without a name linking them. They belong to one person at one time. 36.8 °C and 72 bpm is an ordinary resting pair.

Example

#include <iostream>
using namespace std;

struct Vitals {
  double temp_c;
  int bpm;
};

int main() {
  Vitals p = {36.8, 72};
  cout << p.temp_c << " C, " << p.bpm << " bpm" << endl;
  return 0;
}

FAQ: C++ Structures

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ struct examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ struct in this C++ C++ lesson (C++ Structures).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.