C++ syntax basics: what is the only technical difference between a struct and a class in C++ (ignoring stylistic conventions)?

Difficulty: Easy

Correct Answer: Member function and data are by default public in structures but private in classes.

Explanation:


Introduction / Context:
In modern C++, structs and classes are nearly identical constructs. The notable distinction is their default access level, which affects encapsulation when you omit explicit access specifiers.



Given Data / Assumptions:

  • Both struct and class can contain data members, member functions, constructors, destructors, and even inheritance.
  • Access specifiers available: public, protected, private.
  • We focus on defaults when none are specified.



Concept / Approach:
By default, members of a struct are public; members of a class are private. Likewise for base-class inheritance: struct defaults to public inheritance, class to private inheritance. Otherwise, capabilities are the same. You can override defaults with explicit access specifiers.



Step-by-Step Solution:
1) struct S { int x; }; → x is public by default.2) class C { int x; }; → x is private by default.3) struct D : Base {}; → public inheritance by default; class E : Base {}; → private by default.4) Functionality (constructors, operators, templates) is shared; only defaults differ.



Verification / Alternative check:
Compile code accessing S::x directly vs C::x; you will see that access to C::x fails unless made public.



Why Other Options Are Wrong:
Protected-by-default: incorrect for both forms.“Structs cannot have member functions”: false—structs are classes under a different keyword.



Common Pitfalls:
Assuming “struct is C-style POD only”—not true in C++; use struct for passive aggregates by convention, but it has full class features.



Final Answer:
Member function and data are by default public in structures but private in classes.


More Questions from Objects and Classes

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion