ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Logger {
public:
    static Logger& instance() {
        static Logger inst;
        return inst;
    }
    void log(const string& msg) { cout << msg << " "; }
private:
    Logger() { cout << "created "; }
};
int main() {
    Logger::instance().log("first");
    Logger::instance().log("second");
}
  1. A. created first second
  2. B. created first created second
  3. C. first second
  4. D. Compilation error: Logger's constructor is private

Correct answer: A. created first second

This is the classic Meyers singleton: the function-local static `inst` is constructed exactly once, the first time instance() is called, printing "created ". Both calls return a reference to that same instance, so subsequent calls skip construction entirely: "created first second".

More OOP with C++ and Java questions

Exams that ask this topic