0

So I have this file

template <typename T>
class TestStatic {
public:
    static int staticVal;
};

//static member initialization
template<typename T> int TestStatic<T>::staticVal;

I don’t understand why I have to instantiate the Staticval isn’t it already instantiated in the class definition? Also does it generate a static variable for each template parameter types?

Thanks in advance.

Alex
  • 840
  • 7
  • 23

2 Answers2

2

This line:

static int staticVal;

inside the class is a declaration, not a definition. That's why you have to define it outside the class like this:

template<typename T> 
int TestStatic<T>::staticVal = 0;

And yes, this will generate a definition of the member for all types T.

Alternatively, you could define the static variable inline, like this:

template <typename T>
class TestStatic {
public:
   inline static int staticVal = 0;
};

which has the same semantics as above, but let's you avoid having to define the static variable separately outside the class.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • No, non-static data members are different. Each object of this class has its own copy, so you don't have to worry about it. – cigien May 23 '20 at 19:34
  • As I inferred in my previous comment, one of the difference is that there is only one static member for all instances of a class, but separate copies of non-static members in each instance. – cigien May 23 '20 at 19:35
  • Thank you, But why do copies of non-static members define them? – Alex May 23 '20 at 19:37
  • I'm sorry, I don't understand your question. Refer to the textbook, or resource that you are currently using, and if it still doesn't make sense, perhaps ask a separate specific question. – cigien May 23 '20 at 19:39
  • Let's say I have one member in a `class1` `int a` and another `class2` with `static int b` and nothing else, both are declared but not defined. So why don't I need to do `class1::a = 0` but I need to do `class2::b = 0`? – Alex May 23 '20 at 19:44
  • Because there is no `class1::a`. Instead there is `class1 c; c.a;` – cigien May 23 '20 at 19:45
1

As the variables declared as static are initialized only once as they are allocated space in separate static storage so, the static variables in a class are shared by the objects. There can not be multiple copies of the same static variables for different objects. Also because of this reason static variables can not be initialized using constructors.

Please refer for more information: Reference

Ganesh M S
  • 1,073
  • 2
  • 13
  • 24