ProgrammingHardProduct-company placement · C++
Which function returns a reference that is SAFE to use after the call returns?
- A. int& f() { int x = 1; return x; }
- B. int& g() { static int x = 1; return x; }
- C. const int& h() { return 5; }
- D. int& k(int x) { return x; }
Correct answer: B. int& g() { static int x = 1; return x; }
A static local lives until the program ends. The others return references to a local variable, a temporary or a by-value parameter, all destroyed when the function returns, leaving a dangling reference.
More OOP with C++ and Java questions
- Why does a C++ copy assignment operator conventionally return T& (that is, this)?
- What is printed? cpp // C++17 struct V { int d[2] = {1, 2}; int& operator[](int i) { cout << "N"; return d[i]; } int operator[](int i)…
- Which lines fail to compile? cpp struct E { explicit E(int) { } }; int main() { E a(1); // L1 E b{1}; // L2 E c = 1; // L3 E d = {1}; //…
- Which line fails to compile? cpp struct P { const int id; }; int main() { P a{1}, b{2}; P c = a; // L1 a = b; // L2 }
- How many of these statements about implicitly generated special members in C++11 and later are correct? (i) If a class declares a copy…
- What happens when this is compiled? cpp struct A { A(int) { } }; int main() { A a; }