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
C++ Classes and Objects
C++ Constructors and Destructors
C++ Access Specifiers and Encapsulation
C++ Inheritance
C++ Polymorphism and Virtual Functions
C++ Abstract Classes and Interfaces
C++ Operator Overloading
Exercises & Assignments
Build a BankAccount class
Calculate areas with polymorphism
Overload operators for a Money class
Interview Questions & Answers
What is the difference between struct and class in C++?
What is a constructor in C++ and what are its types?
What is a destructor in C++?
What is the difference between overloading and overriding in C++?
What is a virtual function in C++?
What is a pure virtual function and an abstract class in C++?
What is the static keyword in C++?