ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
struct N {
int v = 0;
N& operator++() { cout << "pre "; ++v; return *this; }
N operator++(int) { cout << "post "; N t = *this; ++v; return t; }
};
int main() {
N n;
++n;
n++;
N m = n++;
++(++n);
cout << n.v << " " << m.v;
}- A. pre post post pre pre 5 3
- B. pre post post pre pre 5 2
- C. pre post post pre 4 2
- D. pre post post pre pre 4 2
Correct answer: B. pre post post pre pre 5 2
++n calls the prefix operator (v = 1); n++ calls the postfix operator, the one with the dummy int parameter (v = 2). N m = n++ copies the old value into m (m.v = 2) and increments n to 3. ++(++n) works because prefix ++ returns a reference to n itself, so both increments apply to n: v = 5. If prefix returned by value, the outer ++ would increment a temporary copy and n.v would be 4.
More OOP with C++ and Java questions
- What is printed? java String s = "a,b,,c,,"; System.out.print(s.split(",").length);
- What is printed? java System.out.print(",x,".split(",").length + " " + "".split(",").length);
- What is printed? java String a = "Aa", b = "BB"; Set<String> set = new HashSet<>(); set.add(a); set.add(b); System.out.print((a.hashCode()…
- What is printed? java PriorityQueue<String> pq = new PriorityQueue<>( Comparator.comparing(String::length).thenComparing(Comparator.reverse…
- What is printed? java Set<String> s = new TreeSet<>(Comparator.comparingInt(String::length)); s.add("one"); s.add("two"); s.add("three")…
- What is printed? java int[] a = {3, 1, 2}; Integer[] b = {3, 1, 2}; System.out.print(Arrays.asList(a).size() + " " +…