Struct vs Class in C++
In C++, struct and class are nearly identical, with only one difference in their default access level.
Key Differences
| Feature | Struct | Class |
|---|---|---|
| Default access modifier | public | private |
| Default inheritance | public | private |
| Intended use (convention) | Passive data structures | Objects with behavior |
Example
struct Point {
int x; // public by default
int y; // public by default
};
class Circle {
private: // private by default, but explicitly shown for clarity
Point center;
double radius;
public:
Circle(Point c, double r) : center(c), radius(r) {}
double area() const { return 3.14159 * radius * radius; }
};
When to Use Each
- Use
structwhen you have a simple data structure with little or no behavior - Use
classwhen you have an object with both data and behavior that operates on that data - Use
structwhen all members should be publicly accessible - Use
classwhen you need to enforce encapsulation by making some members private
The choice between struct and class is often a matter of convention and communicating intent to other programmers.