Exercise: Questions on Static Keyword


Questions on Static Keyword : Question 1 :
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();
}

0 0
5 5
0 5
Compiler Error
Show Answer
Questions on 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;
}

Compiler Error
1 2 3
1 1 1
3 3 3
0 0 0
Show Answer
Questions on Static Keyword : Question 3 :
Which of the following is true?

Static methods cannot be overloaded.
Static data members can only be accessed by static methods.
Non-static data members can be accessed by static methods.
Static methods can only access static members (data and methods)
Show Answer
Questions on Static Keyword : Question 4 :
Predict the output of following C++ program.
#include <iostream>
using namespace std;

class A
{
private:
    int x;
public:
    A(int _x)  {  x = _x; }
    int get()  { return x; }
};

class B
{
    static A a;
public:
   static int get()
   {  return a.get(); }
};

int main(void)
{
    B b;
    cout << b.get();
    return 0;
}

0
Linker Error: Undefined reference B::a
Linker Error: Cannot access static a
Linker Error: multiple functions with same name get()
Show Answer
Questions on Static Keyword : Question 5 :
#include<iostream>
using namespace std;

class Test
{
private:
    static int count;
public:
    Test& fun(); 
};

int Test::count = 0;

Test& Test::fun()
{
    Test::count++;
    cout << Test::count << " ";
    return *this;
}

int main()
{
    Test t;
    t.fun().fun().fun().fun();
    return 0;
}

Compiler Error
4 4 4 4
1 1 1 1
1 2 3 4
Show Answer
Questions on Static Keyword : Question 6 :
Output of following C++ program?
#include <iostream>
class Test
{
public:
    void fun();
};
static void Test::fun()   
{
    std::cout<<"fun() is static\n";
}
int main()
{
    Test::fun();   
    return 0;
}
Contributed by Pravasi Meet

fun() is static
Empty Screen
Compiler Error
Show Answer