Intermediate7 min readLesson 33 of 50
What is a struct?
A struct is like a class but with public as the default access specifier. Structs are ideal for plain data containers without complex behavior.
#include <iostream>
using namespace std;
struct Point {
double x;
double y;
double distanceTo(const Point& other) {
double dx = x - other.x;
double dy = y - other.y;
return sqrt(dx*dx + dy*dy);
}
};
int main() {
Point p1 = {0.0, 0.0};
Point p2 = {3.0, 4.0};
cout << "Distance: " << p1.distanceTo(p2) << endl; // 5
return 0;
}
Output:
Distance: 5
struct vs class
| Feature | struct | class |
| Default access | public | private |
| Default inheritance | public | private |
| Can have methods | Yes | Yes |
| Best for | Simple data bundles (POD) | Complex OOP with encapsulation |
Array of Structs
struct Student {
string name;
int score;
};
Student students[3] = {
{"Alice", 95},
{"Bob", 82},
{"Carol", 78}
};
for (const Student& s : students) {
cout << s.name << ": " << s.score << endl;
}
Exercise
Create a Book struct with title, author, year, and price. Declare an array of 3 books and print the title of the most expensive one.
Show Solution
#include <iostream>
using namespace std;
struct Book {
string title, author;
int year;
double price;
};
int main() {
Book books[] = {
{"C++ Primer", "Lippman", 2012, 49.99},
{"Effective C++", "Meyers", 2005, 39.99},
{"The C++ Programming Language", "Stroustrup", 2013, 55.00}
};
Book& mostExpensive = books[0];
for (Book& b : books)
if (b.price > mostExpensive.price) mostExpensive = b;
cout << "Most expensive: " << mostExpensive.title << endl;
return 0;
}
Quiz
What is the default access specifier for struct members?
- A) private
- B) protected
- C) public
- D) internal
Answer
C) public
Summary
- Structs group related data; members are public by default.
- Structs can have constructors and methods like classes.
- Use structs for simple data bundles; classes for complex OOP.