C++ | Templates | Question 4

Output of following program?

#include <iostream>
using namespace std;

template <class T>
class Test
{
private:
    T val;
public:
    static int count;
    Test()  {   count++;   }
};

template<class T>
int Test<T>::count = 0;

int main()
{
    Test<int> a;
    Test<int> b;
    Test<double> c;
    cout << Test<int>::count   << endl;
    cout << Test<double>::count << endl;
    return 0;
}

(A)

0
0

(B)

1
1

(C)

2
1

(D)

1
0


Answer: (C)

Explanation: There are two classes created by the template: Test and Test.

Since count is a static member, every class has its own copy of it. Also, count gets incremented in constructor.

Quiz of this Question






Practice Tags :

Recommended Posts:



3 Average Difficulty : 3/5.0
Based on 1 vote(s)