C++ data members: which category is shared by all instances of the class?
-
APublic
-
BInherited
-
CStatic
-
DFriend
Answer
Correct Answer: Static
Explanation
Introduction / Context:Class design often distinguishes between per-object state and per-class state. When a value should be common across all objects (for example, a counter of instances or a configuration flag), C++ provides a specific storage class and access pattern to model this: static data members. Understanding this distinction avoids redundant storage and keeps invariants centralized.
Given Data / Assumptions:
- Per-object members exist separately in each instance.
- Per-class members exist once regardless of the number of instances.
- Access control (public/private/protected) is independent from whether a member is static or non-static.
Concept / Approach:
A static data member is allocated once and shared among all instances of the class. It can be accessed via the class name (e.g., T::count) or through an object (though the former is clearer). Public/private affects visibility, not multiplicity. “Inherited” is not a storage class; it merely describes where names come from in hierarchies. “Friend” is an access grant, not a data member category. Hence, the only option that encodes “shared by all instances” is static.
Step-by-Step Solution:
Identify need: single storage shared across objects. Choose static data member and define it (and, in pre-C++17, provide an out-of-class definition). Access it via ClassName::member for clarity and encapsulate with static member functions if needed.Verification / Alternative check:
Instantiate several objects and modify a static member through one of them; observe the updated value through all others and via the class name, confirming shared storage.
Why Other Options Are Wrong:
Public — concerns visibility, not sharing.
Inherited — not a storage specifier.
Friend — grants access to another function/class; not a member kind.
Common Pitfalls:
- Forgetting to define non-inline static data members in a translation unit (before C++17).
- Confusing static data members with static local variables inside functions.
Final Answer:
Static