cpp / beginner
Snippet
Structs vs Classes: What's the Difference?
In C++, structs and classes are nearly identical - both can have member functions, access specifiers, and constructors. The key difference is their default access level: structs default to public, classes default to private. Structs are traditionally used for simple data containers (POD - Plain Old Data), while classes are used when you need encapsulation and data hiding. For modern C++, the choice is mostly stylistic.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>struct PointStruct {int x;int y;void print() {std::cout << "Struct: (" << x << ", " << y << ")" << std::endl;}};class PointClass {public:int x;int y;void print() {std::cout << "Class: (" << x << ", " << y << ")" << std::endl;}};int main() {PointStruct s1 = {10, 20};s1.print();PointClass c1;c1.x = 30;c1.y = 40;c1.print();PointStruct s2;s2.x = 50;s2.y = 60;s2.print();return 0;}
Breakdown
1
struct PointStruct {
Struct definition - members default to public access
2
int x; int y;
Public member variables by default in structs
3
PointStruct s1 = {10, 20};
Aggregate initialization allowed with structs
4
class PointClass {
Class definition - members default to private access
5
public:
Explicit access specifier needed to make members accessible
6
c1.x = 30;
Accessing public members of a class object