HiveBrain v1.2.0
Get Started
← Back to all entries
principlecppCritical

When should you use a class vs a struct in C++?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
youstructshouldclassusewhen

Problem

In what scenarios is it better to use a struct vs a class in C++?

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.

Context

Stack Overflow Q#54585, score: 1139

Revisions (0)

No revisions yet.