tags:

views:

107

answers:

6

Hi,

#include "stdafx.h"
#include<iostream.h>

template<class T>
class Sample
{
    public:
        Sample();
        static int i;



};
template<class T>
int Sample<T>::i = 0;
template<class T>
Sample<T>::Sample()
{
    i++;
    cout<<i;
}

void main()
{
    Sample<int>s1;
    Sample<float>s2;
    Sample<char>s3;
}

output: 111

what is the reason i am getting out put is 111?

+1  A: 

Sample<int>::i, Sample<float>::i and Sample<char>::i are three different variables. Hence you're getting 111.

KennyTM
+1  A: 

Sample is a class template that is used to create three distinct classes in this case, each with its own distinct i.

Marcelo Cantos
+7  A: 

The reason that the output is 111 (as opposed to 123) is that Sample<int>, Sample<float> and Sample<char> are three completely different types, and therefore they each have their own, separate static variable called i.

You have a template called Sample, and each time you instantiate it with a different template argument, it uses that template to create a new class on the fly, based on the template. But the classes created using the template do not have a relationship to each other, and do not share static information.

Tyler McHenry
A: 

When you have a template class with a static member variable the compiler is supposed to ensure that for "each" typename T, there is one and only one copy of the static variable. Since you have instantiated Sample class with three different types, you see the output as "1" for each type.

Abhay
A: 

Sample<int>, Sample<float>, Sample<char> are three different types and each has its own static variable.

If you wanted to get 123 you would have had to put static int i in a common base class.

Gregory Pakosz
+2  A: 

Try adding the line

Sample<float> s2_2;

to main() (which should return an int, incidentally). This should help to illustrate what others have already answered.

In addition, you could include the type information in your output:

#include <typeinfo>
:
:
template<class T>
Sample<T>::Sample()
{
    i++;
    std::cout << typeid(T).name() << ':' << i << std::endl;
}
Johnsyweb