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();
}- A. Created Created Created
- B. Created
- C. Nothing is printed
- 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
- What is printed? cpp struct Base { int level = 1; }; struct Mid : Base { int level = 2; }; struct Leaf : Mid { int level = 3; void show()…
- What is printed? java public class Main { static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } public…
- What is printed? java class Box<T> { private T value; void set(T v) { value = v; } T get() { return value; } } public class Main { public…
- What is printed? java public class Main { public static void main(String[] args) { Integer a = 127; Integer b = 127; Integer c = 200…
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…
- What is printed? java class Base { void show() { System.out.print("Base"); } } class Sub extends Base { void show() {…