Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C++ | Static Keyword | Question 1

  • Last Updated : 28 Jun, 2021

Predict the output of following C++ program.

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

#include <iostream>
using namespace std;
class Test
    static int x;
    Test() { x++; }
    static int getX() {return x;}
int Test::x = 0;
int main()
    cout << Test::getX() << " ";
    Test t[5];
    cout << Test::getX();

(A) 0 0
(B) 5 5
(C) 0 5
(D) Compiler Error

Answer: (C)

Explanation: Static functions can be called without any object. So the call “Test::getX()” is fine.

Since x is initialized as 0, the first call to getX() returns 0. Note the statement x++ in constructor. When an array of 5 objects is created, the constructor is called 5 times. So x is incremented to 5 before the next call to getX().

Quiz of this Question

My Personal Notes arrow_drop_up
Recommended Articles
Page :