ProgrammingHardProduct-company placement · C++
A global object g1 defined in file1.cpp uses the global object g2 defined in file2.cpp inside g1's constructor. Both have dynamic initialisation. What does the C++ standard guarantee?
- A. g2 is always initialised first because it is used by g1
- B. Globals are initialised in alphabetical order of their file names
- C. The linker reorders initialisation to satisfy dependencies
- D. Nothing about which one is initialised first, so g1 may see g2 before it is constructed
Correct answer: D. Nothing about which one is initialised first, so g1 may see g2 before it is constructed
Initialisation order is defined within one translation unit (definition order) but unspecified across translation units: the 'static initialisation order fiasco'. A function-local static (construct on first use) avoids it.
More OOP with C++ and Java questions
- What is printed? cpp void f(int) { cout << "I"; } void f(char) { cout << "P"; } int main() { f(0); f(nullptr); }
- Which lines fail to compile? cpp void g(int& x) { } void h(const int& x) { } int main() { int a = 1; g(5); // L1 h(5); // L2 g(a); // L3…
- What is printed? cpp void f(int&) { cout << "N"; } void f(const int&) { cout << "C"; } int main() { int a = 1; f(a); f(5); }
- What is printed? cpp void f(int&) { cout << "L"; } void f(int&&) { cout << "R"; } int main() { int a = 1; int&& r = 5; f(a); f(5)…
- What is printed? cpp struct A { A() { cout << "D"; } A(const A&) { cout << "C"; } A(A&&) noexcept { cout << "M"; } }; int main() {…
- What is printed? cpp int main() { uniqueptr<int> p = makeunique<int>(7); uniqueptr<int> q = std::move(p); cout << (p == nullptr) << q; }