ProgrammingHardProduct-company placement · C++
What happens when this is compiled?
What happens when this is compiled?
struct A {
int v = 0;
int& get() const { return v; }
};- A. It compiles; get() returns a modifiable reference
- B. Compile-time error: cannot bind int& to the const member v
- C. It compiles but writing through the reference is undefined behaviour
- D. Compile-time error: const functions cannot return references
Correct answer: B. Compile-time error: cannot bind int& to the const member v
Inside a const member function this points to a const A, so v is a const int and cannot initialise a non-const int&. Returning const int& (or by value) fixes it.
More OOP with C++ and Java questions
- A global object g1 defined in file1.cpp uses the global object g2 defined in file2.cpp inside g1's constructor. Both have dynamic…
- 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() {…