ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Singleton {
    static Singleton *instance;
    Singleton() { cout << "Created "; }
public:
    static Singleton* get() {
        if (!instance) instance = new Singleton();
        return instance;
    }
};
Singleton* Singleton::instance = nullptr;
int main() {
    Singleton::get();
    Singleton::get();
    Singleton::get();
}
  1. A. Created Created Created
  2. B. Created
  3. C. Nothing is printed
  4. D. Compile-time error: the constructor is private but called from a static member

Correct answer: B. Created

instance starts as nullptr; the first get() call constructs the single Singleton (printing Created) and caches the pointer. The next two calls see instance already non-null and simply return the cached pointer without constructing again, so Created prints only once in total.

More OOP with C++ and Java questions

Exams that ask this topic