Question discussion

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

912Medium DSSSB TGT Computer Science 0 replies 2 views
0

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

#include <iostream>
using namespace std;
class C { public: static int n; C() { n++; } };
int C::n = 0;
int main() {
    C a, b;
    C *p = new C[3];
    cout << C::n;
}
  • A2
  • B5
  • C4
  • D3
Correct answer: B

Explanation

The static counter is shared by all objects: 2 (a, b) + 3 (array elements) = 5 constructor calls.

Discussion 0

Nobody has replied yet. Start the discussion!