LearnFrenzy
Sign in Take a free test

OOPS Concepts · Find the Error · Question 8

Error: creating an object with a private constructor Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>

class Logger {
    Logger() {}
public:
    static Logger& instance() { static Logger l; return l; }
    void log(const char* m) { std::cout << m << '\n'; }
};

int main() {
    Logger mine;
    mine.log("hi");
    return 0;
}
  • A log must be static
  • B The constructor is private (a singleton design), so main cannot create a Logger; use Logger::instance().log("hi") Correct
  • C instance must return a pointer
  • D Logger needs a destructor
Correct Answer: Option B

Private constructors restrict object creation to the class itself – here to the single static instance.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links