Topic 25 of 83
Structures
Overview
Structures group variables of different data types under a single name. They are the precursor to classes and are heavily used to represent data records.
Syntax
cpp
struct Player {
string name;
int health;
int score;
};
// Instantiation
Player p1;
p1.name = "Hero";
p1.health = 100;
// Initialization list
Player p2 = {"Villain", 150, 500};Common Pitfalls
- Forgetting the semicolon `;` at the very end of the struct definition.
Interview Tips
- Explain the difference between a `struct` and a `class` in C++. In C++, they are almost identical, except struct members are `public` by default, while class members are `private` by default.
Real-World Example
Managing a list of objects using structs.
example
cpp
#include <iostream>
#include <vector>
using namespace std;
struct Point {
int x, y;
};
int main() {
vector<Point> path = {{0,0}, {1,2}, {3,5}};
for (const auto& pt : path) {
cout << "Going to: (" << pt.x << "," << pt.y << ")\n";
}
return 0;
}