In C++ classes, which statement about the accessibility of data members and member functions is correct (considering typical design, not a special case)?

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:

  • C++ supports access specifiers: public, protected, private.
  • There is no rule that “must” requires data or functions to be of a specific access.
  • Constructors can be private (e.g., singletons, factories, non-instantiable bases).


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:

Evaluate A: “must be private” → false (permitted, but not mandated). Evaluate B: correct—members can be public or private (and also protected). Evaluate C: “must be private” for functions → false. Evaluate D: “constructor cannot be private” → false; private constructors are legal.


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:

  • Forgetting that protected is also available; B remains correct because it does not exclude protected, it merely states a possibility.
  • Confusing best practices with language rules.


Final Answer:

Both data and functions can be either private or public.

More Questions from Objects and Classes

Discussion & Comments

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