When should you use a class vs a struct in C++?
c++, class, ooad, oop, struct
Solution
The differences between a `class` and a `struct` in C++ are:
- `struct` members and base classes/structs are `public` by default.
- `class` members and base classes/structs are `private` by default.
Both classes and structs can have a mixture of `public`, `protected` and `private` members, can use inheritance, and can have member functions.
I would recommend you:
- use `struct` for plain-old-data structures without any class-like features;
- use `class` when you make use of features such as `private` or `protected` members, non-default constructors and operators, etc.
Problem
In what scenarios is it better to use a `struct` vs a `class` in C++?
Related problems
- typedef struct vs struct definitions
- Why is there not an std::is_struct type trait?
- What is a lambda expression, and when should I use one?
- Do these members have unspecified ordering?
- What are the differences between struct and class in C++?
- What are POD types in C++?
- Visual C++ 2015 linker error when forward declaring a struct as class
- What are the differences between struct and class in C++?