C++ | Static Keyword | Question 2
#include <iostream> using namespace std; class Player { private: int id; static int next_id; public: 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; } |
chevron_right
filter_none
(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.
Recommended Posts:
- C++ | Static Keyword | Question 1
- C++ | Static Keyword | Question 6
- C++ | Static Keyword | Question 3
- C++ | Static Keyword | Question 4
- C++ | Static Keyword | Question 5
- Static Keyword in C++
- Comparison of static keyword in C++ and Java
- Output of Java Programs | Set 48 (Static keyword)
- Understanding "static" in "public static void main" in Java
- Difference between static and non-static variables in Java
- Difference between static and non-static method in Java
- C++ | friend keyword | Question 1
- C++ | const keyword | Question 5
- C++ | const keyword | Question 5
- C++ | friend keyword | Question 2



