ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
struct R { int v = 0; R& inc() { v++; return *this; } };
struct V { int v = 0; V inc() { v++; return *this; } };
int main() {
R r; V w;
r.inc().inc().inc();
w.inc().inc().inc();
cout << r.v << " " << w.v;
}- A. 1 1
- B. 3 3
- C. 3 1
- D. 1 3
Correct answer: C. 3 1
R::inc returns a reference, so each chained call works on r itself: 3. V::inc returns a copy, so only the first call touches w (v = 1); the next two increment temporary copies.
More OOP with C++ and Java questions
- What is printed? cpp int a = 5; int &r = a; r = 10; int b = 20; r = b; b = 30; cout << a << " " << r;
- What is printed? java class R implements AutoCloseable { String n; R(String n) { this.n = n; System.out.print("o" + n + " "); } public…
- What is printed? cpp struct B { virtual void f(int x = 1) { cout << "B" << x; } }; struct D : B { void f(int x = 2) override { cout << "D"…
- What is printed? java class T { static String hi() { return "hi"; } } // in main: T t = null; System.out.print(t.hi());
- What is printed? java char x = 'A'; int i = 0; System.out.print(true ? 1 : 2.0); System.out.print(" "); System.out.print(true ? x : i);
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout << "Bd"; } }; struct D : B { void f(double) { cout <<…