In C++, struct
and class
are nearly identical, with only one difference in their default access level.
Feature | Struct | Class |
---|---|---|
Default access modifier | public | private |
Default inheritance | public | private |
Intended use (convention) | Passive data structures | Objects with behavior |
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; }
};
struct
when you have a simple data structure with little or no behaviorclass
when you have an object with both data and behavior that operates on that datastruct
when all members should be publicly accessibleclass
when you need to enforce encapsulation by making some members privateThe choice between struct
and class
is often a matter of convention and communicating intent to other programmers.