Difficulty: Easy
Correct Answer: Both data and functions can be either private or public.
Explanation:
Introduction / Context:
C++ allows fine-grained control of member accessibility using public, protected, and private. Sound encapsulation often suggests keeping data private and exposing behavior publicly, but the language does not force this pattern. This question checks your understanding that both data and functions may use any access specifier as needed by the design.
Given Data / Assumptions:
Concept / Approach:
The language allows members (data or functions) to be declared under any access section. Design guidelines frequently recommend private data and public interface, but that is a convention, not a rule. Moreover, constructors may be private to restrict creation, often paired with static factory functions or friend creators.
Step-by-Step Solution:
Verification / Alternative check:
Write a class with public data (not recommended, but legal) and private methods (also legal). The compiler accepts both. Provide a private constructor and a static create() to confirm private construction is permitted.
Why Other Options Are Wrong:
A and C impose nonexistent requirements.
D misunderstands constructor accessibility; private constructors are valid.
Common Pitfalls:
Final Answer:
Both data and functions can be either private or public.
Discussion & Comments