ProgrammingHardMicrosoft/Google SDE MCQ · GATE CS
What is printed?
What is printed?
struct Counter {
int n = 0;
Counter& add(int k) { n += k; return *this; }
Counter addCopy(int k) { n += k; return *this; }
};
int main() {
Counter c;
c.add(1).add(2);
c.addCopy(10).addCopy(20);
cout << c.n;
}- A. 33
- B. 13
- C. 3
- D. 11
Correct answer: B. 13
add returns a reference, so the chain keeps modifying c: n = 3. addCopy changes c (n = 13) but returns a copy, and the second addCopy(20) modifies only that temporary, so c.n is 13.
More OOP with C++ and Java questions
- Which statement about virtual functions and templates in C++ is correct?
- What is printed? cpp struct B { B() { cout << "B"; } B(const B&) { cout << "c"; } }; struct D : B { D() { cout << "D"; } D(const D&) {…
- What is printed? cpp struct P { int x; explicit P(int v) : x(v) { } explicit operator bool() const { return x != 0; } }; int main() { P…
- Which of the marked lines are compile errors? cpp int g(int x) { return x; } double g(int x) { return 2.0 x; } // line 1 void h(int x) { }…
- What is printed? java Map<String, Integer> m = new HashMap<>(); System.out.print(m.put("a", 1)); System.out.print(m.put("a", 2))…
- What is printed? java Map<String, Integer> m = new HashMap<>(); m.merge("k", 5, Integer::sum); m.merge("k", 5, Integer::sum); m.merge("k"…