Reputation: 7529
I'm fairly inexperienced with C++ and I'm trying to understand what this code does.
template <typename T>
class System : public BaseSystem
{
[..]
private:
static SystemType sysType;
};
Outside the class definition there is something like this:
template <typename T>
SystemType System<T>::sysType= IDGen<BaseSystem>::GenerateNextID();
Is this setting the sysType
field in the System
class to a new ID? But since the sysType
field is private
how is it able to access it? Also, why is the type included before the assignment?
If I wanted to change a field I would do something like field = newvalue;
however this Foo field = newvalue;
seems like it's creating a new field of type Foo
and then assigning it.
Can anyone explain what is that line of code doing?
Upvotes: 3
Views: 6948
Reputation: 320531
It is not an "assignment". It is the definition of the static data member sysType
of your class. In your case the syntax contains quite a bit of template-related stuff, but the immediate matter in question has nothing to do with templates at all. A minimalistic example of the same thing might look as follows
class SomeClass {
...
static int i; // declaration of `SomeClass::i`
...
};
int SomeClass::i = 42; // definition of `SomeClass::i`
All static members of the class have to be defined somewhere (with some exceptions for constant integral members). What you have inside the class is a mere declaration.
So, one more time: every time you declare a static data member in your class, you will have to define it somewhere outside of the class, following the general One Definition Rule for data objects with external linkage, i.e. you have to define in your program once and only once.
In your case the definition includes an initializer. The =
is a part of the initialization syntax. It has nothing to do with assignment.
The access protection does not come into play here at all. In this case you are not accessing a class member, you are defining it. Just like you define private member functions outside of the class, you define private static members outside of the class.
Upvotes: 8