Home | Projects | Notes > C++ Programming > Structs vs. Classes
In addition to define a class we can declare a struct.
struct comes from the C programming language.
In C, we create structs as a container for data, much like a record in many other programming languages.
C++ also supports struct since it has to be compatible with C.
However, it adds the ability to treat structs very much like classes.
Essentially the same as a class except that members are public by default. (With classes, members are private by default.)
struct
Use struct for passive objects with public access
Don't declare methods in struct
class
Use class for active objects with complex behavior an private access
Implement getters/setters as needed
Implement member methods as needed
These guidelines are very general. But, remember! Other C++ programmers will likely be modifying and extending your code. So, don't use C++ in a way that's very different from what C++ programmers expect. For example, don't use a struct and then make everything in the struct so it behaves like a class, just use a class instead.
Class
xxxxxxxxxx101class Person2{3 // Members are private by default4 std::string name;5 std::string get_name();6};7
8Person p;9p.name = "Jack"; // Compiler ERROR - private10std::cout << p.get_name(); // Compiler ERROR - privateStruct
xxxxxxxxxx101struct Person2{3 // Members are public by default4 std::string name;5 std::string get_name(); 6};7
8Person p;9p.name = "Jack"; // OK - public10std::cout << p.get_name(); // OK - public