Jaskamal Kainth

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

The choice between struct and class is often a matter of convention and communicating intent to other programmers.