What are the differences between struct and class in C++?
Why Interviewers Ask This
This question targets practical, hands-on experience with C++. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
In C++, struct and class are nearly identical — only one default difference: The only difference: struct has public members and public inheritance by default; class has private members and private inheritance by default. struct Point { int x; int y; }; // x and y are public class Point { int x; int y; }; // x and y are PRIVATE struct Point { }; // Same as class Point : public Base {}; // class Point : private Base {}; // Same as. That's it — struct supports all C++ features: constructors, destructors, virtual functions, templates, inheritance, access specifiers. Idiomatic usage (convention, not language rule): use struct for: passive data aggregates without invariants (POD — Plain Old Data), simple data holders, things conceptually "like C structs," function parameter bundles, return multiple values. struct Point { double x, y; }; struct Config { std::string host; int port = 8080; bool ssl = true; };. Use class for: objects with behavior, encapsulation, invariants, non-trivial lifetimes. class BankAccount { // invariant: balance >= 0 double balance; public: void deposit(double amount); };. POD (Plain Old Data) types: structs with no user-defined constructors, no virtual functions, no reference members, no private/protected members — layout-compatible with C. Can be memcpy'd. Aggregate initialization: Point p = {1.0, 2.0}; // Requires aggregate type. std::pair and std::tuple: standard library provides pre-built value aggregates for most cases.
Common Mistake
Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real C++ project.