Ad space (banner)
Lesson 16 / 20

Structs (struct)

This lesson covers struct, used to bundle several pieces of data together. It's for anyone searching "C++ struct usage."

struct works very similarly to a class, letting you bundle multiple pieces of data into one type. The main difference from class in C++ is that a struct's members are public by default.

The example defines a struct, struct Point { double x; double y; };, and uses it to represent two coordinates.

A common early mistake is being unsure when to use struct versus class. A common convention: use struct when you just want to bundle plain data, and class when you want to attach a lot of behavior (member functions).

In real projects, structs are used to represent a simple bundle of data โ€” a coordinate, an RGB color, a set of settings, and so on.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C++ directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)