These are the notes for C++ episode 11. In episode 10 our report card was spread over separate arrays: names in one, marks in another, roll numbers in a third. Here you will see exactly how that breaks (a student printed with someone else's roll number), and then invent the struct: your own type that keeps one student's name, roll number and marks together. You will use the dot operator, fill a struct with braces, build an array of structs, pass structs to functions (by value, by reference, by const reference), reach a struct through a pointer with the arrow operator ->, and put a struct inside another struct. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; the outputs and error messages are copied from those runs.
The problem: three registers for one class
A teacher keeps three registers: one for names, one for roll numbers, one for marks. Position 0 in every register is Ravi, position 1 is Priya, and so on. The only thing that links "Ravi", "11" and "65" is that they sit at the same position, and we have to keep those positions in step by hand.
In code, that's three parallel arrays (arrays whose matching positions describe the same thing). Now Aman (position 2) leaves the class, so we move Sana up one place:
#include <iostream>
#include <string>
using namespace std;
int main() {
string names[4] = {"Ravi", "Priya", "Aman", "Sana"};
int rolls[4] = {11, 12, 13, 14};
int marks[4] = {65, 92, 78, 88};
// Aman leaves: move Sana up one place
names[2] = names[3];
marks[2] = marks[3];
for (int i = 0; i < 3; i++) {
cout << rolls[i] << " " << names[i];
cout << " " << marks[i] << endl;
}
return 0;
}
Output:
11 Ravi 65
12 Priya 92
13 Sana 88
Look at the last line: 13 is Aman's roll number. Sana's is 14. We moved her name and her marks and forgot her roll number.
Why it failed: nothing in the code says that names[3], rolls[3] and marks[3] belong to one student. They are three unrelated arrays. There is no compiler error and no crash, just a wrong report card. Bugs like this are the worst kind: the program "works".
The fix: one admission form per student
A real school doesn't keep three registers. Every student fills one admission form with boxes for name, roll number and marks. When a student leaves, the whole form leaves.
| At school | In C++ | Meaning |
|---|---|---|
| A blank admission form (Name ___ Roll ___ Marks ___) | struct Student { ... }; |
the design: a new type |
| Ravi's filled form | Student a; |
a variable of that type |
| The "Marks" box on his form | a.marks |
one member (field), picked with the dot |
Your first struct
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int roll;
int marks;
};
int main() {
Student a;
a.name = "Ravi";
a.roll = 11;
a.marks = 65;
cout << a.roll << " " << a.name << " " << a.marks << endl;
return 0;
}
Output:
11 Ravi 65
Line by line:
struct Student { ... };creates a new type calledStudent, just likeintorstring. It does not create any student yet; it only describes what every student has.string name; int roll; int marks;are the members (also called fields) of the struct.Student a;creates one variable of typeStudent: one filled form.a.name = "Ravi";uses the dot operator to pick thenamemember ofa.- The struct is written above
main, because C++ reads top to bottom andmainuses it. Using a type before it is declared giveserror: 'Student' was not declared in this scope.
The semicolon after the closing brace
struct Student {
string name;
int roll;
int marks;
}
g++ says:
main.cpp:9:2: error: expected ';' after struct definition
Unlike a function, a struct's closing brace needs a semicolon after it: };. Everyone forgets this at least once.
A typo in a field name
With a.mark = 65; (no s):
main.cpp:15:7: error: 'struct Student' has no member named 'mark'; did you mean 'marks'?
The compiler knows every box on the form, so a typo is caught before the program runs, and the did you mean hint is usually right. With three loose arrays, the compiler could never check that.
Filling the whole form at once: brace initialisation
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int roll;
int marks;
};
int main() {
Student a = {"Ravi", 11, 65};
Student b = {"Priya", 12, 92};
cout << a.name << " " << a.marks << endl;
cout << b.name << " " << b.marks << endl;
return 0;
}
Output:
Ravi 65
Priya 92
The values in { } go into the members in the order they are declared: name, then roll, then marks. Put them in the wrong order and g++ complains, for example Student a = {11, "Ravi", 65}; gives error: could not convert '11' from 'int' to 'std::string'. Too many values gives error: too many initializers for 'Student'.
An array of structs
Back to the bug. Instead of three arrays, make one array where every slot is a whole Student:
| Slot | name | roll | marks |
|---|---|---|---|
cls[0] |
Ravi | 11 | 65 |
cls[1] |
Priya | 12 | 92 |
cls[2] |
Aman | 13 | 78 |
cls[3] |
Sana | 14 | 88 |
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int roll;
int marks;
};
int main() {
Student cls[4] = {
{"Ravi", 11, 65}, {"Priya", 12, 92},
{"Aman", 13, 78}, {"Sana", 14, 88}
};
cls[2] = cls[3]; // Aman leaves
for (int i = 0; i < 3; i++) {
cout << cls[i].roll << " " << cls[i].name;
cout << " " << cls[i].marks << endl;
}
return 0;
}
Output:
11 Ravi 65
12 Priya 92
14 Sana 88
Sana keeps her own roll number, 14. cls[2] = cls[3]; copies the whole struct, every member at once, so the fields can never drift apart.
cls[i].roll: first pick the slot with[i], then the member with.roll.- Each inner
{ }fills one student. - Assigning one struct to another (
a = b;) copies every member.
Structs and functions: grace marks that vanish
The principal announces 5 grace marks for everyone. We write a function:
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int roll;
int marks;
};
void addGrace(Student s) {
s.marks = s.marks + 5;
}
int main() {
Student a = {"Ravi", 11, 65};
addGrace(a);
cout << a.name << ": " << a.marks << endl;
return 0;
}
Output:
Ravi: 65
The grace marks vanished. A normal parameter is passed by value: the function receives a copy of the whole struct (a photocopy of Ravi's form) and changes only the copy.
The fix is the reference from episode 10. Change one line to void addGrace(Student& s):
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int roll;
int marks;
};
void addGrace(Student& s) {
s.marks = s.marks + 5;
}
int main() {
Student a = {"Ravi", 11, 65};
addGrace(a);
cout << a.name << ": " << a.marks << endl;
return 0;
}
Output:
Ravi: 70
| Parameter | What the function gets | Use it when |
|---|---|---|
Student s |
a copy of every member | the function needs its own copy to play with (rare for big structs) |
Student& s |
the caller's real struct | the function must change it |
const Student& s |
the real struct, read-only, no copy | the function only reads it (printing, comparing) |
A read-only function looks like this:
void printCard(const Student& s) {
cout << s.roll << " " << s.name << " " << s.marks << endl;
}
Pointers to structs and the arrow ->
Structs and pointers meet all the time (and later, objects on the heap). The obvious attempt:
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int roll;
int marks;
};
int main() {
Student a = {"Ravi", 11, 65};
Student* p = &a;
cout << *p.marks << endl;
return 0;
}
g++ says:
main.cpp:14:16: error: request for member 'marks' in 'p', which is of pointer type 'Student*' (maybe you meant to use '->' ?)
Why: the dot runs before the star. So *p.marks means *(p.marks): C++ tried to pick a member of p, which is an address, not a struct.
Two fixes: brackets, (*p).marks (follow the pointer first, then pick the member), or the shortcut made for exactly this, the arrow p->marks:
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int roll;
int marks;
};
int main() {
Student a = {"Ravi", 11, 65};
Student* p = &a;
cout << (*p).marks << endl;
p->marks = 70;
cout << p->name << ": " << a.marks << endl;
return 0;
}
Output:
65
Ravi: 70
Changing p->marks changed a itself, because p holds a's address.
Rule: a struct variable uses the dot (a.marks); a pointer to a struct uses the arrow (p->marks).
Nested structs and default member values
Forms often have a box with smaller boxes inside: date of birth as DD / MM / YYYY. That is a struct of its own, and a Student can contain one. A struct inside a struct is a nested struct. You can also give a member a default value where you declare it.
#include <iostream>
#include <string>
using namespace std;
struct Date {
int d, m, y;
};
struct Student {
string name;
int roll;
int marks = 0;
Date dob;
};
int main() {
Student a;
a.name = "Ravi";
a.dob = {15, 8, 2010};
cout << a.name << " " << a.marks << endl;
cout << "Born: " << a.dob.d << "/" << a.dob.m;
cout << "/" << a.dob.y << endl;
return 0;
}
Output:
Ravi 0
Born: 15/8/2010
Datemust be declared beforeStudent, becauseStudentuses it.a.dob.y: two dots, one per level.int marks = 0;is a default member initialiser: we never seta.marks, so it is 0. Without= 0, anintmember you never set holds garbage (whatever bits were in that memory), so give members sensible defaults.int d, m, y;declares threeintmembers in one line.
How big is a struct?
A struct's size is roughly the sum of its members' sizes (plus some padding the compiler may add for speed). sizeof(Date) is 12 on this machine: three 4-byte ints.
Common mistakes (and the real g++ messages)
| Mistake | Code | What g++ says / what happens | Fix |
|---|---|---|---|
| No semicolon after the struct | struct Student { ... } |
error: expected ';' after struct definition |
struct Student { ... }; |
| Typo in a member name | a.mark = 65; |
error: 'struct Student' has no member named 'mark'; did you mean 'marks'? |
a.marks = 65; |
| Dot on a pointer | cout << *p.marks; |
error: request for member 'marks' in 'p', which is of pointer type 'Student*' (maybe you meant to use '->' ?) |
p->marks or (*p).marks |
| Using the struct before declaring it | Student a; in main, struct written below main |
error: 'Student' was not declared in this scope |
write the struct above main |
| Values in the wrong order | Student a = {11, "Ravi", 65}; |
error: could not convert '11' from 'int' to 'std::string' {aka 'std::__cxx11::basic_string<char>'} |
follow the member order |
| Too many values | Student a = {"Ravi", 11, 65, 99}; |
error: too many initializers for 'Student' |
one value per member |
| Comparing two structs | if (a == b) |
error: no match for 'operator==' (operand types are 'Student' and 'Student') |
compare members: a.roll == b.roll |
| Printing a whole struct | cout << a; |
error: no match for 'operator<<' (operand types are 'std::ostream' ... and 'Student') |
print the members (or overload <<, episode 17) |
| Changing a struct passed by value | void addGrace(Student s) |
no error; the change is lost | void addGrace(Student& s) |
Mini project: the class register
Rao ma'am wants a register that prints every student, the topper (with the right roll number) and the class average. Notice that a struct can be written on one line too: the line breaks are only for us.
#include <iostream>
#include <string>
using namespace std;
struct Student { string name; int roll; int marks; };
int main() {
Student cls[5] = {
{"Ravi", 11, 65}, {"Priya", 12, 92}, {"Aman", 13, 78},
{"Sana", 14, 88}, {"Kabir", 15, 35}
};
Student top = cls[0];
int total = 0;
for (int i = 0; i < 5; i++) {
cout << cls[i].name << " " << cls[i].marks << endl;
total = total + cls[i].marks;
if (cls[i].marks > top.marks) top = cls[i];
}
cout << "Topper: " << top.name << ", roll " << top.roll << endl;
cout << "Average: " << total / 5.0 << endl;
return 0;
}
Output:
Ravi 65
Priya 92
Aman 78
Sana 88
Kabir 35
Topper: Priya, roll 12
Average: 71.6
Because top is a whole Student, her name and roll number come along with her marks automatically. total / 5.0 divides by a double so the average keeps its decimal part (episode 4).
Extend it: count how many students passed (40 or more), and print the lowest scorer.
The next problem: the form has no rules
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int roll;
int marks;
};
int main() {
Student a = {"Ravi", 11, 65};
a.marks = 250; // out of 100!
a.roll = -7;
cout << a.name << " " << a.roll << " " << a.marks << endl;
return 0;
}
Output:
Ravi -7 250
No error. Any line of code, anywhere, can write anything into any member. The struct groups the data, but it can't protect it. In the next episode, the data learns to check what is written into it: classes and objects.
Practice
- Make
struct Book { string title; string author; int pages; };, store 3 books in an array and print the longest one. - Write
void addPages(Book& b, int n)and test it. - Add a nested
Date publishedtoBookand print it asDD/MM/YYYY. - In the class register, count how many students passed (marks of 40 or more).
Solution
1. Keep the index of the longest book so far; compare pages.
#include <iostream>
#include <string>
using namespace std;
struct Book {
string title;
string author;
int pages;
};
int main() {
Book shelf[3] = {
{"Chai and Code", "Meera Iyer", 180},
{"The Night Train", "Arjun Rao", 256},
{"Monsoon Maths", "Neha Joshi", 224}
};
int best = 0;
for (int i = 1; i < 3; i++) {
if (shelf[i].pages > shelf[best].pages) best = i;
}
cout << "Longest: " << shelf[best].title << " (" << shelf[best].pages << " pages)" << endl;
return 0;
}
Output:
Longest: The Night Train (256 pages)
2. Book& so the change reaches the caller's book.
#include <iostream>
#include <string>
using namespace std;
struct Book {
string title;
string author;
int pages;
};
void addPages(Book& b, int n) {
b.pages = b.pages + n;
}
int main() {
Book b = {"The Night Train", "Arjun Rao", 256};
addPages(b, 20);
cout << b.title << ": " << b.pages << " pages" << endl;
return 0;
}
Output:
The Night Train: 276 pages
3. Declare Date first, then use two dots.
#include <iostream>
#include <string>
using namespace std;
struct Date {
int d, m, y;
};
struct Book {
string title;
int pages;
Date published;
};
int main() {
Book b = {"The Night Train", 256, {12, 6, 2024}};
cout << b.title << ", published " << b.published.d << "/"
<< b.published.m << "/" << b.published.y << endl;
return 0;
}
Output:
The Night Train, published 12/6/2024
The nested {12, 6, 2024} fills the Date member inside the outer braces.
4. Add a counter and one if inside the loop.
#include <iostream>
#include <string>
using namespace std;
struct Student { string name; int roll; int marks; };
int main() {
Student cls[5] = {
{"Ravi", 11, 65}, {"Priya", 12, 92}, {"Aman", 13, 78},
{"Sana", 14, 88}, {"Kabir", 15, 35}
};
int passed = 0;
for (int i = 0; i < 5; i++) {
if (cls[i].marks >= 40) passed = passed + 1;
}
cout << "Passed: " << passed << " of 5" << endl;
return 0;
}
Output:
Passed: 4 of 5
Quick quiz
What does this print?
#include <iostream>
#include <string>
using namespace std;
struct Box { int v; };
void bump(Box b) { b.v = b.v + 1; }
void bumpRef(Box& b) { b.v = b.v + 10; }
int main() {
Box x = {1};
bump(x);
bumpRef(x);
cout << x.v << endl;
return 0;
}
- A.
1 - B.
2 - C.
11 - D.
12
Answer
C: 11 (verified). bump receives a copy, so its +1 is lost. bumpRef receives the real x, so +10 sticks: 1 + 10 = 11.
Interview questions
- What is a struct? A user-defined type that groups related values (members) of possibly different types under one name, like
struct Student { string name; int roll; int marks; };. - Why use a struct instead of parallel arrays? The values of one record live together, so they can't drift apart; you can copy, pass and return a whole record at once; and the compiler checks member names.
- What is the difference between
.and->?.picks a member of a struct variable (a.marks).->picks a member through a pointer (p->marks), and is short for(*p).marks. - Why does
*p.marksnot compile? The member operator.has higher precedence than*, so it means*(p.marks), and a pointer has no members. - What happens when you assign one struct to another? Every member is copied (a member-wise copy). The two structs are then independent.
- How should you pass a struct to a function? By
const Student&to read it (no copy), byStudent&to change it, and by value only when the function needs its own copy. - What is the difference between a struct and a class in C++? Only the default access: struct members are public by default, class members are private by default (episode 12).
- Can you compare two structs with
==? Not by default (no match for 'operator=='). Compare members, or defineoperator==(operator overloading, episode 17). - What is a default member initialiser? A value written at the member's declaration, like
int marks = 0;, used when nothing else sets it.
Glossary
| Term | Plain meaning | Example |
|---|---|---|
| Parallel arrays | Several arrays whose matching positions describe the same thing, kept in step by hand | names[2], rolls[2], marks[2] |
| Struct | Your own type that groups related values together | struct Student { ... }; |
| Type | What kind of value a variable holds | int, string, Student |
| User-defined type | A type you create, not one built into C++ | Student |
| Member (field) | One value inside a struct | marks in Student |
Dot operator (.) |
Picks a member of a struct variable | a.marks |
| Declaration | Telling C++ that something exists and what it looks like | struct Student { ... }; |
| Brace initialisation | Filling all members at once with { }, in member order |
Student a = {"Ravi", 11, 65}; |
| Initializer | A value used to fill something when it is created | the 65 in {"Ravi", 11, 65} |
| Array of structs | An array whose every slot is a whole struct | Student cls[4]; |
| Member-wise copy | Copying a struct copies every member | cls[2] = cls[3]; |
| Pass by value | The function gets a copy | void addGrace(Student s) |
| Pass by reference | The function gets the caller's real variable | void addGrace(Student& s) |
| const reference | A read-only reference; no copy is made | const Student& s |
| Pointer to a struct | A variable holding a struct's address | Student* p = &a; |
Arrow operator (->) |
Picks a member through a pointer | p->marks |
| Precedence | Which operator runs first in an expression | . runs before * |
| Nested struct | A struct used as a member of another struct | Date dob; inside Student |
| Default member initialiser | A value given to a member at its declaration | int marks = 0; |
| Garbage value | Whatever leftover bits were in memory; an unset int member holds one |
an int member never set |
sizeof |
How many bytes a type or variable takes | sizeof(Date) is 12 here |
| Padding | Unused bytes the compiler may add inside a struct so members line up for speed | a char followed by an int |
| Record | One complete set of related values, like one student's data | {"Ravi", 11, 65} |
Summary
- Keeping one student's data in parallel arrays breaks easily: we printed Sana with Aman's roll number, with no error at all.
- A struct (
struct Student { string name; int roll; int marks; };) creates a new type whose members travel together. Don't forget the;after}. - The dot operator picks a member:
a.marks. Typos are caught:has no member named 'mark'; did you mean 'marks'?. - Brace initialisation fills a struct in member order:
Student a = {"Ravi", 11, 65};. - An array of structs keeps records in step;
cls[2] = cls[3];copies a whole record. - Pass
Student&to change a struct,const Student&to read it; by value, the function only changes a copy. - Through a pointer, use the arrow:
p->marksis(*p).marks;*p.marksdoesn't compile. - Structs can contain structs (
a.dob.y), and members can have defaults (int marks = 0;). - A struct groups data but can't protect it:
a.marks = 250;is accepted.
Next episode: classes and objects. Today, marks of 250 were accepted without a word. Next time, the data checks what's written into it and refuses bad values: you'll invent classes and objects.