Q. What is the output of the following C++ code?

Code:
#include <iostream>
using namespace std;
 
class A
{
  static int val;
 
   public:
  void write(int i){
    val = i;
  }
  void read(){
    cout << val;
  }
};
 
int main(int argc, char const *argv[])
{
  A a = A();
  a.write(10);
  a.read();
  return 0;
}
  • (A) 10
  • (B) Segmentation fault
  • (C) Compilation error
  • (D) None of the above
πŸ’¬ Discuss
βœ… Correct Answer: (C) Compilation error
Explanation: Each static member of a class is initialized before it is used. As ‘val’ is a static member of class A and is not initialized, the program will display an error.
Explanation by: Dharmendra Sir
Each static member of a class is initialized before it is used. As ‘val’ is a static member of class A and is not initialized, the program will display an error.

πŸ’¬ Discussion


πŸ“Š Question Analytics

πŸ‘οΈ
231
Total Visits
πŸ“½οΈ
4 y ago
Published
πŸŽ–οΈ
Dharmendra Sir
Publisher
πŸ“ˆ
83%
Success Rate