OA. free
Free
Palo Alto Networks Core Computer Science Core Computer Science Medium

What will be the output of the following C++ code?

Palo Alto Networks technical mcq question, verified with a worked answer. Free to practise - no sign-up.

What will be the output of the following C++ code?

#include <iostream>
using namespace std;

class Test {
    static int x;
public:
    Test() { x++; }
    static int getX() { return x; }
};

int Test::x = 0;

int main() {
    cout << Test::getX() << " ";
    Test t[5];
    cout << Test::getX();
    return 0;
}
Choose one option.
Show answer & explanation
Answer: B. 0 5

Initially Test::x is 0, so getX() prints 0. Creating an array of 5 Test objects executes the constructor 5 times, incrementing x to 5, so getX() prints 5.

Step-by-step Derivation:
Step 1: Test::x is statically initialized to 0.
Step 2: Test::getX() called first prints 0.
Step 3: Test t[5] allocates an array of 5 instances, executing Test() 5 times.
Step 4: Each constructor execution increments static x by 1 (x becomes 5).
Step 5: Second Test::getX() call returns and prints 5.
Step 6: Overall output is '0 5'.