ProgrammingModerateProduct-company placement · C++
Why does a C++ copy assignment operator conventionally return T& (that is, *this)?
- A. Because returning void would make the assignment fail to compile
- B. Because returning by value would call the destructor of the left operand
- C. So that assignments can be chained like a = b = c without extra copies, as with built-in types
- D. Because the compiler requires every operator to return a reference
Correct answer: C. So that assignments can be chained like a = b = c without extra copies, as with built-in types
operator= may return anything, but returning a reference to the left operand mirrors built-in assignment, enables chaining and avoids making a needless copy.
More OOP with C++ and Java questions
- 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; }
- What is printed? cpp struct B { virtual void f() { cout << "B"; } }; struct D : B { void f() override { cout << "D"; } }; int main() {…