Structs (struct vs class)
Real data comes in clusters: a point has an x and a y, a student has a name and a score, an order has an item, quantity, and price. A struct lets you bundle those related values into one named type so you can pass them around as a single thing. By the end of this lesson you'll define structs, store them in vectors, give them member functions, and understand exactly how struct and class differ.
Learn Structs (struct vs class) in our free C++ course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick recall.
Part of the free C++ course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn
💡 Real-World Analogy
A struct is a form with labelled fields . A "Contact" form has lines for Name, Phone, and Email — three different bits of information that belong together on one sheet. You don't carry around three loose scraps of paper; you keep one form. In code, a Contact struct holds those fields together, so you can pass one Contact to a function instead of three separate arguments. A class is the same form, but locked in a drawer where you must go through a clerk (public methods) to read or change anything — that's encapsulation.
1. Defining and Using a Struct
You declare a struct with the struct keyword, a name, and a list of members (the fields). Create an instance, then read and write its members with the dot operator . . The tidiest way to set everything at once is aggregate initialization with braces, which fills the members in declaration order. Don't forget the semicolon after the closing brace of the struct definition.
Your turn. Fill in the brace initializer to create a Book with the members in order:
🧩 Reorder Challenge
These lines define a Point struct and use it. Put them in the correct order:
Define the Point type first, before main (A), open main (C), create a point (D), print x + y = 7 (B), then return 0; (E) and close the brace (F). The struct must be declared before it's used.
2. struct vs class
Here's the question every C++ beginner asks. The only language-level difference is the default access level : in a struct , members are public by default; in a class , they're private by default. Everything else — constructors, methods, inheritance — is identical. By convention, programmers use struct for simple bundles of mostly-public data and class for types that hide their internals behind public methods (encapsulation).
📊 struct vs class at a Glance
Aspect
struct
class
Default member access
public
private
Default inheritance
Can have methods?
yes
Can have constructors?
Typical use (convention)
plain data bundle
encapsulated type
3. Structs With Behaviour
A struct isn't limited to data — it can carry constructors (to set up its members) and member functions (to compute things from them). A member function marked const promises not to modify the struct, which both documents intent and lets you call it on const objects. This is exactly where a struct starts to look like a class.
4. A Vector of Structs
The single most useful pattern in everyday C++ is a vector<Struct> — a table of records. Each element is one row (a student, an order, a point), and you can loop, filter, and sort them with a lambda comparator. This combines structs with the vectors, range-based loops, and lambdas you've already learned.
🔎 Deep Dive: initialization styles & passing structs
You have several ways to fill a struct, each with its place:
When passing a struct to a function, remember the cost of copying. Pass by const& to read large structs without a copy, and by & when the function must modify the original:
Pro Tips
- 💡 Use struct for plain data: if the type is just a bundle of public fields, a struct signals that intent.
- 💡 Give members default values: int score = 0; inside the struct avoids uninitialized garbage.
- 💡 Pass big structs by const& : avoid silent copies on every call.
- 💡 Mark non-mutating methods const : it documents intent and works on const objects.
🧠 Quick Recall
Predict the output before revealing the answer.
10 — brace init sets x = 2, y = 5 in order, so 2 * 5 = 10.
No — in a class , v is private by default, so b.v is inaccessible. A struct (public by default) would compile.
6 — area() returns w * h = 2.0 * 3.0 = 6. Structs can have member functions.
Common Errors (and the fix)
- Missing semicolon after the struct: a struct definition must end with }; . Leaving off the semicolon produces a confusing error on the next line.
- Accessing a class member directly: "'x' is private" means you need a public method, or you meant to use a struct .
- Uninitialized members: Point p; cout << p.x; reads garbage. Brace-init it or give members default values.
- Wrong brace order: aggregate init fills members in declaration order — Book{412, "Dune"} mixes up an int and a string and won't compile.
- Copying big structs by value: passing a large struct without const& copies all its members on every call.
📋 Quick Reference
Task
Code
Define a struct
struct P { int x; int y; };
Brace init
P p{3, 4};
Designated init (C++20)
P p{.x = 3, .y = 4};
Access a member
p.x
Vector of structs
vector<P> pts;
Read big struct
void f(const P& p)
Frequently Asked Questions
Mini-Challenge: Inventory Value
Design your own Item struct, store several in a vector, and total their value. This is the exact pattern behind carts, ledgers, and dashboards.
🎉 Lesson Complete
- ✅ A struct bundles related data under one name; access members with .
- ✅ Brace init fills members in order; designated init names them (C++20)
- ✅ The only language difference from class is default access (public vs private)
- ✅ Structs can have constructors and (often const ) member functions
- ✅ A vector<Struct> is the everyday "table of records" — sort it with a lambda
- ✅ Next lesson: Recursion — functions that call themselves
Practice quiz
What is a struct in C++?
- A function that returns multiple values
- A loop construct
- A way to bundle several related variables (members) into one named type
- A pointer to an array
Answer: A way to bundle several related variables (members) into one named type. A struct groups related fields under one name, so you can pass and return them as a single value.
What is the ONLY language-level difference between struct and class in C++?
- Default member access: struct members are public, class members are private by default
- structs cannot have functions
- Only classes can be inherited from
- structs are stored on the heap
Answer: Default member access: struct members are public, class members are private by default. The sole difference is the default access level (and default inheritance): public for struct, private for class.
How do you access a member m of a struct instance p?
- p->m
- p::m
- m(p)
- p.m
Answer: p.m. Use the dot operator on a struct object: p.m.
What does this print? struct P { int x; int y; }; P p{2, 5}; cout << p.x * p.y;
- 7
- 10
- 25
- It does not compile
Answer: 10. Brace init fills members in declaration order, so x = 2 and y = 5, and 2 * 5 = 10.
Does this compile? class Box { int v; }; Box b; b.v = 7;
- No — in a class, v is private by default, so b.v is inaccessible
- Yes, v is public
- Yes, but only inside main
- No, classes cannot have int members
Answer: No — in a class, v is private by default, so b.v is inaccessible. Class members default to private, so b.v can't be accessed from outside. A struct (public by default) would compile.
Can a struct have constructors and member functions?
- No, only classes can
- Only constructors, not member functions
- Yes — structs can have everything a class can; the choice is about convention
- Only if marked 'public struct'
Answer: Yes — structs can have everything a class can; the choice is about convention. Structs and classes are equally capable; struct vs class is about intent, not capability.
What does the const mean in double area() const { return w * h; }?
- The return value cannot change
- The member function promises not to modify the struct, and can be called on const objects
- All members become const
- It makes the function run at compile time
Answer: The member function promises not to modify the struct, and can be called on const objects. A const member function won't modify the object, which documents intent and lets it be called on const instances.
Which initialization style is the C++20 designated initializer for struct Point { int x; int y; };?
- Point p{3, 4};
- Point p(3, 4);
- Point p = 3, 4;
- Point p{.x = 3, .y = 4};
Answer: Point p{.x = 3, .y = 4};. Designated initializers name each member: Point p{.x = 3, .y = 4}; (C++20).
How should you pass a large struct to a function that only reads it?
- By value: f(Struct s)
- By const reference: f(const Struct& s)
- By pointer to pointer
- It must be global
Answer: By const reference: f(const Struct& s). const Struct& avoids copying the whole struct on every call while guaranteeing it won't be modified.
Which everyday pattern represents a 'table of records' you can sort with a lambda?
- A single struct
- A map of ints
- A vector of structs (vector<Struct>)
- A C-style array of chars
Answer: A vector of structs (vector<Struct>). A vector<Struct> holds one record per element and can be sorted with a lambda comparator.
Continue this course
- Previous: Range-Based for Loops
- Next: Recursion