The Wayback Machine - https://web.archive.org/web/20240118173352/https://www.geeksforgeeks.org/c-static-keyword-question-1/
Open In App
Related Articles

C++ | Static Keyword | Question 1

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Predict the output of following C++ program.




#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();
}


(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

Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads