Question
In C++, in which situations is it more appropriate to use a struct instead of a class, and when should you prefer a class instead?
What practical differences matter when designing types in real programs?
Short Answer
By the end of this page, you will understand the technical difference between struct and class in C++, the common coding conventions around each, and how to choose the right one for data-focused types versus behavior-focused types.
Concept
In C++, struct and class are almost the same language feature. The main technical difference is the default access level:
- In a
struct, members arepublicby default. - In a
class, members areprivateby default.
There is one more matching default rule:
structusespublicinheritance by default.classusesprivateinheritance by default.
Example:
struct Point {
int x; // public by default
int y; // public by default
};
class BankAccount {
double balance; // private by default
};
So why do both exist if they are so similar?
Because programmers use them to communicate intent.
A common convention is:
Mental Model
Think of a struct as a clear plastic container and a class as a locked box with buttons on the outside.
- With a
struct, people can see and access the contents directly. - With a
class, the contents are hidden, and people interact with it through approved controls.
Neither is automatically better. The choice depends on whether direct access is safe and useful.
If the object is just holding values, the clear container is convenient. If the object needs to protect its state or enforce rules, the locked box is safer.
Syntax and Examples
Basic syntax
struct Person {
std::string name;
int age;
};
class BankAccount {
double balance;
public:
BankAccount(double initialBalance) : balance(initialBalance) {}
void deposit(double amount) {
balance += amount;
}
double getBalance() const {
return balance;
}
};
Example 1: Use struct for plain data
#include <iostream>
#include <string>
struct UserProfile {
std::string username;
int score;
};
int main() {
UserProfile user{"alice", 120};
std::cout << user.username << " has score " << user.score << ;
}
Step by Step Execution
Consider this example:
#include <iostream>
struct Point {
int x;
int y;
};
class Counter {
int value;
public:
Counter() : value(0) {}
void increment() {
value++;
}
int getValue() const {
return value;
}
};
int main() {
Point p{3, 4};
std::cout << p.x << ", " << p.y << '\n';
Counter c;
c.increment();
c.increment();
std::cout << c.getValue() << '\n';
}
What happens step by step
-
Pointis defined as astruct.
Real World Use Cases
struct and class both appear often in real C++ programs, but usually for different design purposes.
Common uses for struct
- Geometry data: points, rectangles, vectors
- Configuration objects: settings loaded from a file
- DTO-style objects: data transfer between modules
- Simple records: log entries, sensor readings, parsed values
- Public aggregate data: values that are naturally open
Example:
struct AppConfig {
std::string host;
int port;
bool debug;
};
Common uses for class
- Objects with invariants: account balances, validated IDs
- Business logic types: orders, carts, services
- Resource management: file wrappers, sockets, mutex guards
- APIs with controlled usage: types with clear public methods
- Libraries: types that may evolve without exposing internals
Example:
class FileLogger {
std::string path;
public:
: path(filePath) {}
;
};
Real Codebase Usage
In real codebases, the choice is often based on convention, maintainability, and encapsulation, not on language limitations.
Common team conventions
Many C++ teams follow this rule of thumb:
struct= passive dataclass= active object with rules and behavior
This makes large codebases easier to scan.
Patterns developers use
1. Data carriers with struct
struct HttpResponse {
int statusCode;
std::string body;
std::string contentType;
};
This is easy to create, return, and inspect.
2. Validation and invariants with class
class Age {
int value;
public:
explicit Age(int v) {
if (v < 0) {
throw std::invalid_argument("Age cannot be negative");
}
value = v;
}
{
value;
}
};
Common Mistakes
1. Thinking struct is only for C-style code
In C++, struct is a full-featured type.
It can have methods, constructors, operators, and private members.
struct Timer {
private:
int seconds;
public:
Timer() : seconds(0) {}
void tick() { seconds++; }
};
2. Assuming class and struct behave completely differently
They do not. The biggest built-in difference is the default access and default inheritance.
3. Exposing data that should be protected
Broken design:
class BankAccount {
public:
double balance;
};
This lets anyone set balance to an invalid value.
Better:
class {
balance;
:
}
{
(amount > ) {
balance += amount;
}
}
{
balance;
}
};
Comparisons
| Topic | struct | class |
|---|---|---|
| Default member access | public | private |
| Default inheritance | public | private |
| Can have methods? | Yes | Yes |
| Can have constructors? | Yes | Yes |
| Can have private members? | Yes | Yes |
| Typical use | Plain data, simple records | Encapsulation, behavior, invariants |
| Signals to readers | Open data |
Cheat Sheet
structandclassare almost the same in C++.- Main difference:
structmembers arepublicby defaultclassmembers areprivateby default
- Inheritance default:
struct Derived : Basemeanspublicinheritanceclass Derived : Basemeansprivateinheritance
Use struct when
- the type is mainly a bundle of related values
- direct access is acceptable
- there are few or no invariants to protect
- you want a lightweight data object
Use class when
- internal state should be hidden
- the object must enforce rules
- you want a clear public API
- the implementation may change later
Quick examples
struct Point {
x;
y;
};
{
value;
:
() : () {}
{ value++; }
{ value; }
};
FAQ
Is there any real difference between struct and class in C++?
Yes, but it is small. The main difference is the default access level and default inheritance. Otherwise, they support almost the same features.
Should I always use class in modern C++?
No. struct is still very useful for simple data types and is common in modern C++ code.
Is struct less object-oriented than class?
No. A struct can have methods, constructors, operators, and private members. It is still a full C++ type.
Why do many examples use struct for small data types?
Because public fields are often the clearest design for simple records like points, colors, or settings.
When should I switch from a struct to a class?
Switch when the type starts needing validation, hidden state, controlled updates, or a more stable public interface.
Can a struct have private members?
Yes.
struct {
:
secret;
};
Mini Project
Description
Create a small C++ program that models two different kinds of types: a simple public data record and an encapsulated object with rules. This project demonstrates why struct is a good fit for plain data, while class is better when you need to protect state and control how it changes.
Goal
Build a program that uses a struct for a public user profile and a class for a bank account with safe deposit and withdrawal behavior.
Requirements
- Create a
structnamedUserProfilewith public fields for name and age. - Create a
classnamedBankAccountwith a private balance. - Add public methods to deposit money, withdraw money, and read the current balance.
- Prevent withdrawals that would make the balance negative.
- In
main(), create both types and print their data/results.
Keep learning
Related questions
Basic Rules and Idioms for Operator Overloading in C++
Learn the core rules, syntax, and common idioms for operator overloading in C++, including member vs non-member operators.
C++ Casts Explained: C-Style Cast vs static_cast vs dynamic_cast
Learn the difference between C-style casts, static_cast, and dynamic_cast in C++ with clear examples, safety rules, and real usage tips.
C++ Lambda Expressions Explained: What They Are and When to Use Them
Learn what C++ lambda expressions are, why they exist, when to use them, and how they simplify callbacks, algorithms, and local logic.