C++ Programming Questions and Answers – Static Members
This set of C++ Programming Multiple Choice Questions & Answers (MCQs) focuses on “Static Members”.
1.
What will be the output of the following C++ code?
#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 0
c) 0 5
d) 5 5
2.
What will be the output of the following C++ code?
#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;
}
a) 1 2 3
b) 2 2 2
c) 1 3 1
d) 1 1 1
3.
Which of the following is correct about static variables?
a) Static functions do not support polymorphism
b) Static data members cannot be accessed by non-static member functions
c) Static data members functions can access only static data members
d) Static data members functions can access both static and non-static data members
4.
What will be the output of the following C++ code?
#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;
}
a) Garbage value
b) Compile-time Error
c) Run-time Error
d) Nothing is printed
5.
What will be the output of the following C++ code?
#include<iostream>
using namespace std;
class Test
{
private:
static int count;
public:
void fun();
};
int Test::count;
void Test::fun()
{
count++;
cout << count << " ";
}
int main()
{
Test t;
t.fun();
return 0;
}
a) 0
b) Cannot Say
c) 1
d) Error




