ProgrammingHardTCS NQT · Infosys interview pattern
What is printed?
What is printed?
struct V {
int x;
V(int a) : x(a) {}
V operator+(const V& o) const { return V(x + o.x * 2); }
};
int main() {
V a(1), b(2), c(3);
cout << (a + b + c).x;
}- A. 17
- B. 6
- C. 11
- D. 9
Correct answer: C. 11
+ is left-associative: (a + b) = V(1 + 2 × 2) = V(5); then V(5) + c = V(5 + 3 × 2) = V(11). Grouping a + (b + c) gives 1 + 8 × 2 = 17, ignoring the × 2 gives 6, and doubling only the last operand gives 1 + 2 + 6 = 9.
More OOP with C++ and Java questions
- What is printed? java class A { void m(A a) { System.out.print("AA"); } } class B extends A { void m(A a) { System.out.print("BA"); } void…
- Class P is in package a and declares protected int x. Class C is in package b and extends P. Inside an instance method of C, which of…
- What happens when this Java class is compiled? java class Util { static void f(List<String> l) { } static void f(List<Integer> l) { } }
- How many of the following statements about equals() and hashCode() in Java are correct? (i) If a.equals(b) is true, a.hashCode() must…
- On a typical 64-bit compiler (8-byte pointers, 4-byte int, natural alignment), what does sizeof(P) print? cpp class P { int id; public…
- What is printed? java class P { static { System.out.print("1"); } { System.out.print("2"); } P() { System.out.print("3"); } } class C…