Open In App
Related Articles

C++ | Static Keyword | Question 2

Improve Article
Save Article
Like Article

#include <iostream>
using namespace std;
class Player
    int id;
    static int next_id;
    int getID() { return id; }
    Player()  {  id = next_id++; }
int Player::next_id = 1;
int main()
  Player p1;
  Player p2;
  Player p3;
  cout << p1.getID() << " ";
  cout << p2.getID() << " ";
  cout << p3.getID();
  return 0;

(A) Compiler Error
(B) 1 2 3
(C) 1 1 1
(D) 3 3 3
(E) 0 0 0

Answer: (B)

Explanation: If a member variable is declared static, all objects of that class have access to a single instance of that variable. Static variables are sometimes called class variables, class fields, or class-wide fields because they don’t belong to a specific object; they belong to the class.

In the above code, static variable next_id is used to assign a unique id to all objects.

Quiz of this Question

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!

Last Updated : 28 Jun, 2021
Like Article
Save Article
Similar Reads