What is the difference between struct and class in C++?

In C++, struct and class are almost the same. Both can have methods, constructors and inheritance. The only differences are the default access (and the default inheritance type).

#include <iostream>

struct S { int x = 1; };           // x is public
class C { int x = 2; public: int get() const { return x; } };   // x is private

int main() {
    S s;
    C c;
    std::cout << s.x << ' ' << c.get() << '\n';
}
Output

1 2

By habit: use struct for simple data, and class for objects with rules (invariants) and behavior. See Classes and Objects.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.