Question discussion

What is the output of the following C++ program?#include using namespace std; class C { int v; public: C() : v(0) {} C add(int x) { v += x;…

2187Medium DSSSB TGT Computer Science 0 replies 1 views
0

What is the output of the following C++ program?

#include <iostream>
using namespace std;
class C {
    int v;
public:
    C() : v(0) {}
    C add(int x) { v += x; return *this; }
    int get() const { return v; }
};
int main() {
    C c;
    c.add(1).add(2).add(3);
    cout << c.get();
    return 0;
}
  • A6
  • B1
  • C3
  • D0
Correct answer: B

Explanation

add() returns a copy by value, so only the first call modifies c; the next two calls modify temporary copies, leaving c.v = 1.

Discussion 0

Nobody has replied yet. Start the discussion!