Struct vs Class in C++: Key Differences and Usage
struct and class are very similar, but struct members are public by default while class members are private by default. Both can have functions, constructors, and inheritance, but their default access levels and typical usage differ.Quick Comparison
Here is a quick side-by-side comparison of struct and class in C++.
| Feature | struct | class |
|---|---|---|
| Default member access | public | private |
| Default inheritance access | public | private |
| Typical usage | Plain data structures, simple grouping | Complex data with encapsulation and behavior |
| Supports member functions | Yes | Yes |
| Supports constructors/destructors | Yes | Yes |
| Supports inheritance | Yes | Yes |
Key Differences
The main difference between struct and class in C++ lies in their default access levels. In a struct, all members (variables and functions) are public by default, meaning they can be accessed from outside the struct without restrictions. In contrast, a class has all members private by default, so they cannot be accessed directly from outside unless explicitly declared public.
Another difference is the default inheritance mode. When you inherit from a struct, the inheritance is public by default, but when inheriting from a class, it is private by default. This affects how derived classes can access base class members.
Despite these differences, both struct and class can have member functions, constructors, destructors, and support inheritance. The choice between them is often about style and intent: struct is usually used for simple data holders, while class is preferred for encapsulating data with behavior and enforcing access control.
Code Comparison
Here is an example showing a struct with public members by default.
#include <iostream>
struct Point {
int x;
int y;
void move(int dx, int dy) {
x += dx;
y += dy;
}
};
int main() {
Point p{1, 2};
std::cout << "Before move: (" << p.x << ", " << p.y << ")\n";
p.move(3, 4);
std::cout << "After move: (" << p.x << ", " << p.y << ")\n";
return 0;
}Class Equivalent
The same example using a class requires explicit public access to allow outside access.
#include <iostream> class Point { public: int x; int y; void move(int dx, int dy) { x += dx; y += dy; } }; int main() { Point p{1, 2}; std::cout << "Before move: (" << p.x << ", " << p.y << ")\n"; p.move(3, 4); std::cout << "After move: (" << p.x << ", " << p.y << ")\n"; return 0; }
When to Use Which
Choose struct when you want a simple data container with public access by default, like grouping related variables without complex behavior. It is ideal for plain data structures or POD (Plain Old Data) types.
Choose class when you want to encapsulate data and control access strictly, hiding implementation details and exposing only what is necessary. Use class for objects with behavior, invariants, and when you want to enforce encapsulation and abstraction.