C++ | Templates | Question 4

Output of following program?

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


(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



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.