ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
int f() { std::cout << "f "; return 1; }
int g() { std::cout << "g "; return 2; }
int a = f();
int b = g();
int main() { }- A. Unspecified order: could be either
- B. f g
- C. g f
- D. Nothing, since a and b are never used
Correct answer: B. f g
Globals in the same translation unit are guaranteed to initialize in the order they are declared, so f() runs (printing 'f') before g() (printing 'g') — unlike the unspecified order across different translation units.
More OOP with C++ and Java questions
- What is printed? cpp struct X { int id; X(int i) : id(i) { std::cout << "X" << id << " "; } ~X() { std::cout << "~X" << id << " "; } }…
- What is printed? cpp struct Animal { void speak() { std::cout << "Animal"; } }; struct Dog : Animal { void speak() { std::cout << "Dog"; }…
- What is wrong with this generic class? java class Factory<T> { T create() { return new T(); } }
- What is printed? java class A { static int x = init("x", 1); static { System.out.print("sA "); } static int y = init("y", 2); static int…
- What is printed? cpp struct Base { virtual void f() { std::cout << "Base "; } }; struct Mid : Base { }; struct Derived : Mid { void f()…
- What is printed? cpp struct Base { Base(){ std::cout << "Base "; } }; struct Mem { Mem(){ std::cout << "Mem "; } }; struct Derived : Base…