ProgrammingHardProduct-company placement · C++
Which lines fail to compile?
Which lines fail to compile?
void g(int& x) { }
void h(const int& x) { }
int main() {
int a = 1;
g(5); // L1
h(5); // L2
g(a); // L3
g(a + 1); // L4
}- A. L1 only
- B. L1, L2 and L4
- C. L4 only
- D. L1 and L4
Correct answer: D. L1 and L4
A non-const lvalue reference cannot bind to a temporary (5 or a + 1). A const reference can, by binding to a materialised temporary.
More OOP with C++ and Java questions
- 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; }
- What is printed? cpp int main() { auto a = makeshared<int>(5); auto b = a; { auto c = a; cout << a.usecount(); } cout << a.usecount()…
- What is printed? cpp int main() { weakptr<int> w; { auto s = makeshared<int>(1); w = s; cout << w.expired(); } cout << w.expired(); }