Difficulty: Easy
Correct Answer: Singleton class
Explanation:
Introduction:
Sometimes an application needs exactly one global access point to a resource—logging, configuration, or a device manager. This question targets the standard design pattern that enforces a single instance for a class.
Given Data / Assumptions:
Concept / Approach:
The Singleton pattern ensures only one object exists by controlling construction and providing a global accessor. Typical elements include a private constructor, a deleted copy/move, and a static function that returns a reference to the unique instance, often implemented as a function-local static for thread-safe initialization.
Step-by-Step Solution:
1) Make constructors private or protected.2) Delete copy/move operations to prevent cloning.3) Provide static T& instance() { static T obj; return obj; }4) Access via T::instance() and never via direct construction.
Verification / Alternative check:
Attempts to create additional instances should fail to compile or link; all users obtain the same object reference from the accessor.
Why Other Options Are Wrong:
Virtual class: C++ has virtual inheritance, not “virtual classes.”Abstract class: prevents instantiation altogether unless derived and completed.Friend class: an access control tool, not a single-instance mechanism.
Common Pitfalls:
Overusing singletons creates hidden dependencies and hinders testing. Prefer dependency injection; use a singleton only when global uniqueness is genuinely required.
Final Answer:
Singleton class
Discussion & Comments